<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 2015-11-21
 */
namespace app\mobile\controller;

use app\home\logic\UsersLogic;
use app\home\model\Message;
use think\Page;
use think\Request;
use think\Verify;
use think\db;
use think\Session;
use phpDocumentor\Reflection\DocBlock\Tag\VarTag;

class User extends MobileBase
{

    public $user_id = 0;
    public $user = array();

    /*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where("user_id", $user['user_id'])->find();
            session('user', $user);  //覆盖session 中的 user
            if($user['pay_gold']>100 && !empty($user['pay_gold'])){
            	$user['pay_gold_TX'] = number_format($user['pay_gold'] * 0.3, 2, '.', '');
            }
            else{
            	$user['pay_gold_TX'] = '0.00';
            }
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
        }
        $nologin = array(
            'login', 'pop_login', 'do_login', 'logout', 'verify', 'set_pwd', 'finished',
            'verifyHandle', 'reg', 'send_sms_reg_code', 'find_pwd', 'check_validate_code',
            'forget_pwd', 'check_captcha', 'check_username', 'send_validate_code', 'express',
        );
        if (!$this->user_id && !in_array(ACTION_NAME, $nologin)) {
            header("location:" . U('Mobile/User/login'));
            exit;
        }

        $order_status_coment = array(
            'WAITPAY' => '待付款 ', //订单查询状态 待支付
            'WAITSEND' => '待发货', //订单查询状态 待发货
            'WAITRECEIVE' => '待收货', //订单查询状态 待收货
            'WAITCCOMMENT' => '待评价', //订单查询状态 待评价
        );
        
        $order_cellar_status = array(
            0 => '未发货',//提酒订单中表示未发货
            1 => '已发货',//提酒订单中表示已发货
            2 => '已完成',
            3 => '已备货', //自提时，进行备货确认
            5 => '已作废',//提酒订单中表示订单已被取消，可删除
        );
        
        $shpipping_status_content = array(
            '0' => '无轨迹',
            '1' => '已揽收',
            '2' => '在途中',
            '3' => '已签收',
            '4' => '问题件',
            '201' => '到达派件城市',
        );
        $this->assign('order_cellar_status', $order_cellar_status);
        $this->assign('shpipping_status_content', $shpipping_status_content);
        $this->assign('shpipping_status_content', $shpipping_status_content);
        $this->assign('order_status_coment', $order_status_coment);
    }

    
    /*
     * 用户中心首页
     */
    public function index()
    {  
        $goods_collect_count = M('goods_collect')->where("user_id", $this->user_id)->count(); // 我的商品收藏
        $comment_count = M('comment')->where("user_id", $this->user_id)->count();   // 我的评论数
        $coupon_count = M('coupon_list')->where("uid", $this->user_id)->count(); // 我的优惠券数量
//      $level_name = M('user_level')->where("level_id", $this->user['level'])->getField('level_name'); // 等级名称
        $order_count = M('order')->where("user_id", $this->user_id)->count(); //我的全部订单 (改)
        $count_return = M('return_goods')->where("user_id=$this->user_id and status<2")->count();   //退换货数量
        $wait_pay = M('order')->where("user_id=$this->user_id and pay_status =0 and order_status = 0  and pay_code != 'cod'")->count(); //我的待付款 (改)
        $wait_shipping = M('order')->where("user_id=$this->user_id and order_status in(0,1) and pay_status=1 and shipping_status= 0")->count(); //我的待发货 (改)
        $wait_receive = M('order')->where("user_id=$this->user_id and order_status= 1 and shipping_status= 1")->count(); //我的待收货 (改)
        $comment_sql = "select COUNT(1) as comment from f_order_goods as og left join f_order as o on o.order_id = og.order_id where o.user_id = $this->user_id and og.is_send = 1 and og.is_comment = 0 and o.order_status in (2,4)";

        $comment = DB::query($comment_sql);  //我的待评论订单
        $wait_comment = $comment[0][comment];
        $count_sundry_status = array('wait_pay'=>$wait_pay, 'wait_shipping'=>$wait_shipping, 'wait_receive'=>$wait_receive, 'wait_comment'=>$wait_comment, 'count_return'=>$count_return);
        $yesterday_income = M('user_income')->where(array('uid'=>$this->user_id,'type'=>0,'source'=>0))->whereTime('add_time', 'yesterday')->getField('SUM(amount)');
        $yesterday_income = empty($yesterday_income)?0:$yesterday_income;
        //未查看消息
        $my_message = M("user_message")->where(array("user_id"=>$this->user_id,"status"=>0))->select();
        $is_mobile_validate = is_mobile_validate();
        $this->assign('is_mobile_validate',$is_mobile_validate); 
        
        //判断用户是否参与抢红包
        $is_red_packet = M('red_packet')->where('user_id',$this->user_id)->find();
        $is_red_packet = empty($is_red_packet)?0:1;
        $this->assign('is_red_packet',$is_red_packet);
        $this->assign('message_count',count($my_message));
        
        //用户星级
        $stars = user_stars($this->user_id);
        $this->assign('stars',$stars);
        $vip_level = vip_level($this->user_id);
        $vip_level = empty($vip_level)?0:$vip_level;
        $this->assign('vip_level',$vip_level);
//      $this->assign('level_name', $level_name);
        $this->assign('order_count', $order_count); // 我的订单数 （改）
        $this->assign('goods_collect_count', $goods_collect_count);
        $this->assign('yesterday_income',sprintf("%.2f", $yesterday_income));
        $this->assign('comment_count', $comment_count);
        $this->assign('coupon_count', $coupon_count);
        $this->assign('count_sundry_status', $count_sundry_status);  //各种数量
        return $this->fetch();
    }
    
    


    public function logout()
    {
        session_unset();
        session_destroy();
        setcookie('cn', '', time() - 3600, '/');
        setcookie('user_id', '', time() - 3600, '/');
        //$this->success("退出成功",U('Mobile/Index/index'));
        header("Location:" . U('Mobile/Index/index'));
        exit();
    }

    /*
     * 账户资金
     */
    public function account()
    {
        $user = session('user');
        //获取账户资金记录
        $logic = new UsersLogic();
        $data = $logic->get_account_log($this->user_id, I('get.type'));
        $account_log = $data['result'];

        $this->assign('user', $user);
        $this->assign('account_log', $account_log);
        $this->assign('page', $data['show']);

        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_account_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 优惠券
     */
    public function coupon()
    {
        $logic = new UsersLogic();
        $data = $logic->get_coupon($this->user_id, input('type'));
        $coupon_list = $data['result'];
        $this->assign('coupon_list', $coupon_list);
        $this->assign('page', $data['show']);
        if (input('is_ajax')) {
            return $this->fetch('ajax_coupon_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 确定订单的使用优惠券
     * @author lxl
     * @time 2017
     */
    public function checkcoupon()
    {
        $cartLogic = new \app\home\logic\CartLogic();
        // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
        $result = $cartLogic->cartList($this->user, $this->session_id,1,1); // 获取购物车商品
        if(I('type') == ''){
            $where = " c2.uid = {$this->user_id} and ".time()." < c1.use_end_time and c1.condition <= {$result['total_price']['total_fee']} ";
        }
        if(I('type') == '1'){
           $where = " c2.uid = {$this->user_id} and c1.use_end_time < ".time()." or {$result['total_price']['total_fee']}  < c1.condition ";
        }

        $coupon_list = DB::name('coupon')
            ->alias('c1')
            ->field('c1.name,c1.money,c1.condition,c1.use_end_time, c2.*')
            ->join('coupon_list c2','c2.cid = c1.id and c1.type in(0,1,2,3) and order_id = 0','LEFT')
            ->where($where)
            ->select();
        $this->assign('coupon_list', $coupon_list); // 优惠券列表
        return $this->fetch();
    }

    /**
     *  登录
     */
    public function login()
    {
        if ($this->user_id > 0) {
//
//            header("Location: " . U('Mobile/User/index'));
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Mobile/User/index");
        $this->assign('referurl', $referurl);
        return $this->fetch();
    }

    /**
     * 登录
     */
    public function do_login()
    {
        $username = I('post.username');
        $password = I('post.password');
        $username = trim($username);
        $password = trim($password);
        $remember = I('post.remember');   //一个月免登陆 ，1为是，0为否
        //验证码验证
        $verify_code = I('post.verify_code');
        $verify = new Verify();
        if (!$verify->check($verify_code, 'user_login')) {
            $res = array('status' => 0, 'msg' => '验证码错误');
            exit(json_encode($res));
        }
        $logic = new UsersLogic();
        $res = $logic->login($username, $password);
        if ($res['status'] == 1) {
            $res['url'] = urldecode(I('post.referurl'));
            session('user', $res['result']);
            setcookie('user_id', $res['result']['user_id'], null, '/');
            setcookie('is_distribut', $res['result']['is_distribut'], null, '/');
            $nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];
            setcookie('uname', $nickname, null, '/');
            setcookie('cn', 0, time() - 3600, '/');
            $cartLogic = new \app\home\logic\CartLogic();
            $cartLogic->login_cart_handle($this->session_id, $res['result']['user_id']);  //用户登录后 需要对购物车 一些操作
        }

        exit(json_encode($res));
    }

    /**
     *  注册
     */
    public function reg()
    {

    	if($this->user_id > 0) header("Location: ".U('Mobile/User/index'));
        $reg_sms_enable = tpCache('sms.regis_sms_enable');
        $reg_smtp_enable = tpCache('sms.regis_smtp_enable');

        if (IS_POST) {
            $logic = new UsersLogic();
            //验证码检验
            //$this->verifyHandle('user_reg');
            $username = I('post.username', '');
            $password = I('post.password', '');
            $password2 = I('post.password2', '');
            //是否开启注册验证码机制
            $code = I('post.mobile_code', '');
            $session_id = session_id();
            
            if(check_mobile($username)){
                $check_code = $logic->check_validate_code($code, $username, $session_id);
                if($check_code['status'] != 1){
                    $this->error($check_code['msg']);
                }
            }
            //是否开启注册邮箱验证码机制
            if(check_email($username)){
                $check_code = $logic->check_validate_code($code, $username);
                if($check_code['status'] != 1){
                    $this->error($check_code['msg']);
                }
            }

            $data = $logic->reg($username, $password, $password2);
            if ($data['status'] != 1)
                $this->error($data['msg']);
            session('user', $data['result']);
            setcookie('user_id', $data['result']['user_id'], null, '/');
            setcookie('is_distribut', $data['result']['is_distribut'], null, '/');
            $cartLogic = new \app\home\logic\CartLogic();
            $cartLogic->login_cart_handle($this->session_id, $data['result']['user_id']);  //用户登录后 需要对购物车 一些操作
            $this->success($data['msg'], U('Mobile/User/index'));
            exit;
        }
        $this->assign('regis_sms_enable',$reg_sms_enable); // 注册启用短信：
        $this->assign('regis_smtp_enable',$reg_smtp_enable); // 注册启用邮箱：
        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 120;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
        return $this->fetch();
    }

    /*
     * 订单列表
     */
    public function order_list()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
        if (in_array(strtoupper(I('type')), array('WAITCCOMMENT', 'COMMENTED'))) {
            $where .= " AND order_status in(2,4) and pay_status=1 and shipping_status=1 "; //代评价 和 已评价
        } elseif (I('type')) {
            $where .= C(strtoupper(I('type')));
        }

        $count = M('order')->where($where)->count();
        
        $Page = new Page($count, 10);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        
        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }

        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
        }
        
        //print_r($order_list);
        //exit;

        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('page', $show);
        $this->assign('lists', $order_list);
        $this->assign('active', 'order_list');
        $this->assign('active_status', I('get.type'));
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_order_list');
            exit;
        }
        return $this->fetch();
    }


    /*
     * 订单列表
     */
    public function ajax_order_list()
    {

    }

    /*
     * 订单详情
     */
    public function order_detail()
    {
        $id = I('get.id/d');
        $st = I('st');
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        
//      if($st == 'pay_ok' && $order_info['pay_status']==0){
//      	$r = M('order')->where('order_id',$id)->save(array('pay_status'=>1,'order_status'=>1,'pay_time'=>time()));
//          if($r){
//          	//支付成功，推送微信消息
//              // 如果有微信公众号 则推送一条消息到微信
//              $user = M('users')->where("user_id", $this->user_id)->find();
//              if($user['oauth']== 'weixin')
//              {
//                  $wx_user = M('wx_user')->find();
//                  $jssdk = new \app\mobile\logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
//                  $wx_content = "您的订单:{$order_info['order_sn']} 已支付成功";
//                  $jssdk->push_msg($user['openid'],$wx_content);
//              }
//              //更新订单信息
//              $order_info = M('order')->where($map)->find();
//              $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
//          }
//      } 

        if (!$order_info) {
            $this->error('没有获取到订单信息');
            exit;
        }
        //获取订单商品
        $model = new UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        
        $order_info['goods_list'] = $data['result'];
        
        foreach($order_info['goods_list'] as $key=>$val){
        	$type = M("goods")->where("goods_id",$val['goods_id'])->getField('type');
        	if($type == 1){
	        	if(!empty($val['other_content'])){
		            $other_content = json_decode($val['other_content'],true);
		            $order_info['goods_list'][$key]['other_content'] = $other_content;
		        }
	        }
        }
        
        

        $order_goods_device_list  = array();
        //获取该订单所有运单
        $device_no = M("delivery_doc")->where("order_id",$id)->field("id,invoice_no")->select();
        if(!empty($device_no)){
            foreach ($device_no as $key=>$value){
                foreach ($order_info['goods_list'] as $k=>$v){
                    $v['invoice_no'] = $value['invoice_no'];//填入运单号
                    if(!empty($v['delivery_id'])){
                        if($v['delivery_id'] == $value['id']){
                            $order_goods_device_list[$value['id']][] = $v;
                        }
                    }else{
                        $order_goods_device_list['nodevice'][] = $v;
                    }
                }
            }
	            //无运单的订单去除重复项
	            if(!empty($order_goods_device_list['nodevice'])){
	                $order_goods_device_list['nodevice'] = array_unique($order_goods_device_list['nodevice']);
	            }
        }
        else{
        	$order_goods_device_list['nodevice'] = $order_info['goods_list'];
        }
        

        $order_info['goods_list'] = $order_goods_device_list;


        $region_list = get_region_list();
        $invoice_no = M('DeliveryDoc')->where("order_id", $id)->getField('invoice_no', true);
        $order_info[invoice_no] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id' => $id))->select();
        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('region_list', $region_list);
        $this->assign('order_info', $order_info);
        $this->assign('order_action', $order_action);

        if (I('waitreceive')) {  //待收货详情
            return $this->fetch('wait_receive_detail');
        }
        return $this->fetch();
    }

    public function express()
    {
        $order_id = I('get.order_id/d', 195);
        $order_goods = M('order_goods')->where("order_id", $order_id)->select();
        $delivery = M('delivery_doc')->where("order_id", $order_id)->find();
        $this->assign('order_goods', $order_goods);
        $this->assign('delivery', $delivery);
        return $this->fetch();
    }

    /*
     * 取消订单
     */
    public function cancel_order()
    {
        $id = I('get.id/d');
        //检查是否有积分，余额支付
        $logic = new UsersLogic();
        $data = $logic->cancel_order($this->user_id, $id);
        if ($data['status'] < 0)
            $this->error($data['msg']);
        $this->success($data['msg']);
    }

    /*
     * 用户地址列表
     */
    public function address_list()
    {   
    	$id = I('id/d');//针对一元夺宝地址设置,找出当前一元夺宝使用的地址
    	$indiana_address_id = M('user_indiana')->where('id',$id)->getField('address_id');
    	if(!$indiana_address_id){
    		$indiana_address_id = M('user_address')->where(array('user_id'=>$this->user_id,'is_default'=>1))->getField('address_id'); 
    	}
    	$this->assign('indiana_address_id', $indiana_address_id);
    	
        $address_lists = get_user_address_list($this->user_id);
        $region_list = get_region_list();
        $this->assign('region_list', $region_list);
        $this->assign('lists', $address_lists);
        return $this->fetch();
    }

    /*
     * 添加地址
     */
    public function add_address()
    {
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, 0, I('post.'));
            if ($data['status'] != 1)
                $this->error($data['msg']);
            elseif (I('post.source') == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $data['result'])));
                exit;
            }

            $this->success($data['msg'], U('/Mobile/User/address_list'));
            exit();
        }
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $this->assign('province', $p);
        //return $this->fetch('edit_address');
        return $this->fetch();

    }

    /*
     * 地址编辑
     */
    public function edit_address()
    {
        $id = I('id/d');
        $address = M('user_address')->where(array('address_id' => $id, 'user_id' => $this->user_id))->find();
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, $id, I('post.'));
            if ($_POST['source'] == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $id)));
                exit;
            } else
                $this->success($data['msg'], U('/Mobile/User/address_list'));
            exit();
        }
        //获取省份
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $c = M('region')->where(array('parent_id' => $address['province'], 'level' => 2))->select();
        $d = M('region')->where(array('parent_id' => $address['city'], 'level' => 3))->select();
        if ($address['twon']) {
            $e = M('region')->where(array('parent_id' => $address['district'], 'level' => 4))->select();
            $this->assign('twon', $e);
        }
        $this->assign('province', $p);
        $this->assign('city', $c);
        $this->assign('district', $d);
        $this->assign('address', $address);
        return $this->fetch();
    }

    /*
     * 设置默认收货地址
     */
    public function set_default()
    {
        $id = I('get.id');
        $source = I('get.source');
        M('user_address')->where(array('user_id' => $this->user_id))->save(array('is_default' => 0));
        M('users')->where(array('user_id'=>$this->user_id))->save(array('address_id'=>$id));
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->save(array('is_default' => 1));
        if ($source == 'cart2') {
            $this->redirect(U('Mobile/Cart/cart2'));
            exit;
        } 

        $this->redirect(U('Mobile/User/address_list'));
        
    }

    /*
     * 地址删除
     */
    public function del_address()
    {
        $id = I('get.id');

        $address = M('user_address')->where("address_id", $id)->find();
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($address['is_default'] == 1) {
            $address2 = M('user_address')->where("user_id", $this->user_id)->find();
            $address2 && M('user_address')->where("address_id", $address2['address_id'])->save(array('is_default' => 1));
        }
        if (!$row)
            $this->error('操作失败', U('User/address_list'));
        else
            $this->success("操作成功", U('User/address_list'));
    }

    /*
     * 评论晒单
     */
    public function comment()
    {
        $user_id = $this->user_id;
        $status = I('get.status');
        $logic = new UsersLogic();
        $result = $logic->get_comment($user_id, $status); //获取评论列表
        $this->assign('comment_list', $result['result']);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_comment_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *添加评论
     */
    public function add_comment()
    {
        if (IS_POST) {
            // 晒图片
            $files = request()->file('comment_img_file');
            $save_url = 'public/upload/comment/' . date('Y', time()) . '/' . date('m-d', time());
            foreach ($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->rule('uniqid')->validate(['size' => 1024 * 1024 * 3, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
                if ($info) {
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $comment_img[] = '/'.$save_url . '/' . $info->getFilename();
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
            if (!empty($comment_img)) {
                $add['img'] = serialize($comment_img);
            }

            $user_info = session('user');
            $logic = new UsersLogic();
            $add['goods_id'] = I('goods_id');
            $add['email'] = $user_info['email'];
            $hide_username = I('hide_username');
            if (empty($hide_username)) {
                $add['username'] = $user_info['nickname'];
            }
            $add['order_id'] = I('order_id');
            $add['service_rank'] = I('service_rank');
            $add['deliver_rank'] = I('deliver_rank');
            $add['goods_rank'] = I('goods_rank');
            $add['is'] = I('goods_rank');
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['add_time'] = time();
            $add['ip_address'] = getIP();
            $add['user_id'] = $this->user_id;

            //添加评论
            $row = $logic->add_comment($add);
            if ($row['status'] == 1) {
                $this->success('评论成功', U('/Mobile/User/order_detail', array('id' => $add['order_id'])));
                exit();
            } else {
                $this->error($row['msg']);
            }
        }
        $rec_id = I('rec_id');
        $order_goods = M('order_goods')->where("rec_id", $rec_id)->find();
        $this->assign('order_goods', $order_goods);
        return $this->fetch();
    }

    /*
     * 个人信息
     */
    public function userinfo()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        if (IS_POST) {
            I('post.nickname') ? $post['nickname'] = I('post.nickname') : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
            I('post.sex') ? $post['sex'] = I('post.sex') : $post['sex'] = 0;  // 性别
            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            I('post.email') ? $post['email'] = I('post.email') : false; //邮箱
            I('post.mobile') ? $post['mobile'] = I('post.mobile') : false; //手机

            $email = I('post.email');
            $mobile = I('post.mobile');
            $code = I('post.mobile_code', '');
            if (!empty($email)) {
                $c = M('users')->where(['email' => input('post.email'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("邮箱已被使用");
            }
            if (!empty($mobile)) {
                $c = M('users')->where(['mobile' => input('post.mobile'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("手机已被使用");
                if (!$code)
                    $this->error('请输入验证码');
                $check_code = $userLogic->check_validate_code($code, $mobile, $this->session_id);
                if ($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }

            if (!$userLogic->update_info($this->user_id, $post))
                $this->error("保存失败");
            $this->success("操作成功");
            exit;
        }
        //  获取省份
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        //  获取订单城市
        $city = M('region')->where(array('parent_id' => $user_info['province'], 'level' => 2))->select();
        //  获取订单地区
        $area = M('region')->where(array('parent_id' => $user_info['city'], 'level' => 3))->select();
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('area', $area);
        $this->assign('user', $user_info);
        $this->assign('sex', C('SEX'));
        //从哪个设置页面进来
        $dispaly = I('action');
        if ($dispaly != '') {
            return $this->fetch("$dispaly");
            exit;
        }
        return $this->fetch();
    }
    
    
    /*
     * 个人信息
     */
    public function userinfo2()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        if (IS_POST) {
            I('post.nickname') ? $post['nickname'] = I('post.nickname') : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
            I('post.sex') ? $post['sex'] = I('post.sex') : $post['sex'] = 0;  // 性别
            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            I('post.email') ? $post['email'] = I('post.email') : false; //邮箱
            I('post.mobile') ? $post['mobile'] = I('post.mobile') : false; //手机

            $email = I('post.email');
            $mobile = I('post.mobile');
            $code = I('post.mobile_code', '');
            if (!empty($email)) {
                $c = M('users')->where(['email' => input('post.email'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("邮箱已被使用");
            }
            if (!empty($mobile)) {
                $c = M('users')->where(['mobile' => input('post.mobile'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("手机已被使用");
                if (!$code)
                    $this->error('请输入验证码');
                $check_code = $userLogic->check_validate_code($code, $mobile, $this->session_id);
                if ($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }

            if (!$userLogic->update_info($this->user_id, $post))
                $this->error("保存失败");
            $this->success("操作成功");
            exit;
        }
        //  获取省份
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        //  获取订单城市
        $city = M('region')->where(array('parent_id' => $user_info['province'], 'level' => 2))->select();
        //  获取订单地区
        $area = M('region')->where(array('parent_id' => $user_info['city'], 'level' => 3))->select();
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('area', $area);
        $this->assign('user', $user_info);
        $this->assign('sex', C('SEX'));
        //从哪个设置页面进来
        $dispaly = I('action');
        if ($dispaly != '') {
            return $this->fetch("$dispaly");
            exit;
        }
        return $this->fetch();
    }

    /*
     * 邮箱验证
     */
    public function email_validate()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step', 1);
        //验证是否未绑定过
        if ($user_info['email_validated'] == 0)
            $step = 2;
        //原邮箱验证是否通过
        if ($user_info['email_validated'] == 1 && session('email_step1') == 1)
            $step = 2;
        if ($user_info['email_validated'] == 1 && session('email_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $email = I('post.email');
            $code = I('post.code');
            $info = session('email_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $email || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('email_code', null);
                    session('email_step1', null);
                    if (!$userLogic->update_email_mobile($email, $this->user_id))
                        $this->error('邮箱已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                } else {
                    session('email_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/email_validate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码邮箱不匹配');
        }
        $this->assign('step', $step);
        return $this->fetch();
    }
    
    /*
    * 手机号是否已存在
    */
    public function is_exist_mobile(){
    	$mobile = I('mobile');
    	$r = M('users')->where('mobile='.$mobile.' and user_id!='.$this->user_id)->find();
    	if ($r){
    		echo json_encode(array('status'=>1,'msg'=>'手机号已存在！'));
    	}
    	else{
    		echo json_encode(array('status'=>-1,'msg'=>'手机号不存在！'));
    	}
    }
    
    
    /*
    * 手机验证
    */
    public function mobile_validate()
    {   
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        if (IS_POST) {
            $mobile = I('post.mobile');
            $code = I('post.code');
            $log = M('sms_log')->where(array('mobile'=>$mobile))->order('id DESC')->find();
            $info['code'] = $log['code'];
            $info['mobile'] = $_COOKIE['mobile'];
            if (!$info['code']) $this->error('验证码已过期，请重新获取！');
            if ($info['mobile'] != $mobile) $this->error('验证手机与接受短信手机不匹配！');
            if ($info['code'] == $code) {
            	if(empty($user_info['password'])){
            		$password = $_COOKIE['mima'];
            	    $r = M('users')->where('user_id',$this->user_id)->save(array('mobile'=>$mobile,'mobile_validated'=>1,'password'=>$password));	
            	}
            	else{
            		$r = M('users')->where('user_id',$this->user_id)->save(array('mobile'=>$mobile,'mobile_validated'=>1));	
            	}
            	
            	$pay_points = tpCache('basic.reg_integral'); // 会员注册赠送积分
            	$dis_silver = tpCache('distribut.dis_silver');// 推广收益
                $dis_silver = (int)$dis_silver;
                if($pay_points > 0){
                	$is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'注册送银酒币活动'))->find();
                	if(!$is_give){
                	    $s = M('users')->where('user_id',$this->user_id)->save(array('pay_points'=>$pay_points));//注册送积分

                	    $leader = M('users')->where('user_id',$this->user_id)->getField('first_leader');
                	    if($leader){
	                	    $leader_pay_points = M('users')->where('user_id',$leader)->getField('pay_points');
	                	    $leader_pay_points += $dis_silver;
	                	    $a = M('users')->where('user_id',$leader)->save(array('pay_points'=>$leader_pay_points));//分销上级获取推广积分
	                	}
	                	else{
	                		$a = false;
	                	}
	                	if($s){
	                		//accountLog($this->user_id,0,$pay_points,'注册送积分活动'); // 记录日志流水[TPshop原始日志流水]
	                        income_action(0,3,'注册送银酒币活动',$pay_points,$this->user_id);//写入流水日志,用户注册收益日志 
	                        if($a){
	                        income_action(0,3,'推广收益',$dis_silver,$leader);//写入流水日志 ,上级收益日志
	                        }
	                        else{
	                        	if($leader){
	                        	   $errorMsg = "UID为".$leader."的分销推广{$dis_silver}银酒币收益发放失败——".date("Y-m-d H:i:s",time())."\r\n";
	                        	   log_error($errorMsg);	
	                        	}
	                        }
	                	}
	                	else{
	                		$errorMsg = "UID为".$user['user_id']."的用户注册赠送".$pay_points."银酒币发放失败——".date("Y-m-d H:i:s",time())."\r\n";
	                        log_error($errorMsg);
	                	}	
                	}
                }
                $this->success('操作成功！',U('User/index'));
            }
            else{
            	$this->error('验证码输入错误');
            }
        }
        $this->assign('user_info', $user_info);
        return $this->fetch();
    }
    
    /**
     * 抢红包
     * */
    public function red_packet(){
        echo "活动已关闭";
        exit();
    	$is_mobile_validate = M("users")->where('user_id',$this->user_id)->getField('mobile_validated');
    	$is_mobile_validate =empty($is_mobile_validate)?0:$is_mobile_validate;
    	if(IS_POST){
			if($is_mobile_validate == 0){
				echo json_encode(array('status'=>-1,'msg'=>'亲，请先绑定手机号哦！'));
				exit;
			}
    	    $is_do = M('red_packet')->where('user_id',$this->user_id)->find();
	    	if($is_do){
	    		echo json_encode(array('status'=>-1,'msg'=>'抱歉，亲，您已参与过！'));
	    	}
	    	else{
	    		Db::transaction(function(){
				    $money = mt_rand(10,20)*0.01;
		    		$data = array(
		    		        'user_id' => $this->user_id,
		    		        'add_time' => time(),
		    		        'money' => $money
		    		);
		    		$a = M("red_packet")->add($data);
		    		$user_money = M("users")->where('user_id',$this->user_id)->getField('user_money');
		    		$user_money += $money;
		    		$b = M("users")->where('user_id',$this->user_id)->save(array('user_money'=>$user_money));
				    if($a&&$b){
				    	income_action(2,3,'抢红包活动',$money,$this->user_id);	//写入流水日志
				    	echo json_encode(array('status'=>1,'money'=>$money));
				    }
				    else{
				    	echo json_encode(array('status'=>-1,'msg'=>'抢红包失败，请再试一次！')); 
				    } 
				});
	    	} 
	    	exit;	
    	}
    	session('from_red_pac',true);//标记来自抢红包页面
    	$list = M('red_packet')->limit('0,15')->order('id DESC')->select();
    	$last_id = M('users')->limit(1)->order('user_id DESC')->getField('user_id');
    	for($i=1;$i<6;$i++){//系统生成大金额红包
    		$j=rand(1,3)+5;
    		$add_list[] = array('id'=>rand(15,20),'money'=>number_format(rand(100,1000)*0.01, 2, '.', ''),'add_time'=>time(),'user_id'=>$last_id+$j);
    	}
    	$list = array_merge($list,$add_list);
    	shuffle($list);
    	$this->assign('list',$list);
    	$this->assign('is_val',$is_mobile_validate);
    	return $this->fetch();	
    }

    /**
     * 用户收藏列表
     */
    public function collect_list()
    {
        $userLogic = new UsersLogic();
        $data = $userLogic->get_goods_collect($this->user_id);
        $this->assign('page', $data['show']);// 赋值分页输出
        $this->assign('goods_list', $data['result']);
        if (IS_AJAX) {      //ajax加载更多
            return $this->fetch('ajax_collect_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *取消收藏
     */
    public function cancel_collect()
    {
        $collect_id = I('collect_id');
        $user_id = $this->user_id;
        if (M('goods_collect')->where(['collect_id' => $collect_id, 'user_id' => $user_id])->delete()) {
            $this->success("取消收藏成功", U('User/collect_list'));
        } else {
            $this->error("取消收藏失败", U('User/collect_list'));
        }
    }

    /**
     * 我的留言
     */
    public function message_list()
    {
        C('TOKEN_ON', true);
        if (IS_POST) {
            $this->verifyHandle('message');

            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $user = session('user');
            $data['user_name'] = $user['nickname'];
            $data['msg_time'] = time();
            if (M('feedback')->add($data)) {
                $this->success("留言成功", U('User/message_list'));
                exit;
            } else {
                $this->error('留言失败', U('User/message_list'));
                exit;
            }
        }
        $msg_type = array(0 => '留言', 1 => '投诉', 2 => '询问', 3 => '售后', 4 => '求购');
        $count = M('feedback')->where("user_id", $this->user_id)->count();
        $Page = new Page($count, 100);
        $Page->rollPage = 2;
        $message = M('feedback')->where("user_id", $this->user_id)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $showpage = $Page->show();
        header("Content-type:text/html;charset=utf-8");
        $this->assign('page', $showpage);
        $this->assign('message', $message);
        $this->assign('msg_type', $msg_type);
        return $this->fetch();
    }

    /**账户明细*/
    public function points()
    {
        $type = I('type', 'all');    //获取类型
        $this->assign('type', $type);
        if ($type == 'recharge') {
            //充值明细
            $count = M('recharge')->where("user_id", $this->user_id)->count();
            $Page = new Page($count, 16);
            $account_log = M('recharge')->where("user_id", $this->user_id)->order('order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else if ($type == 'points') {
            //积分记录明细
            $count = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else {
            //全部
            $count = M('account_log')->where(['user_id' => $this->user_id])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        }
        $showpage = $Page->show();
        $this->assign('account_log', $account_log);
        $this->assign('page', $showpage);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_points');
            exit;
        }
        return $this->fetch();
    }

    /*
     * 密码修改
     */
    public function password()
    {
        //检查是否第三方登录用户
        $logic = new UsersLogic();
        $data = $logic->get_info($this->user_id);
        $user = $data['result'];
        if ($user['mobile'] == '' && $user['email'] == '')
            $this->error('请先到电脑端绑定手机', U('/Mobile/User/index'));
        if (IS_POST) {
            $userLogic = new UsersLogic();
            $data = $userLogic->password($this->user_id, I('post.old_password'), I('post.new_password'), I('post.confirm_password')); // 获取用户信息
            if ($data['status'] == -1)
                $this->error($data['msg']);
            $this->success($data['msg']);
            exit;
        }
        return $this->fetch();
    }

    function forget_pwd()
    {
        if ($this->user_id > 0) {
            $this->redirect("User/Index");
//            header("Location: " . U('User/Index'));`
        }
        $username = I('username');
        if (IS_POST) {
            if (!empty($username)) {
                $this->verifyHandle('forget');
                $field = 'mobile';
                if (check_email($username)) {
                    $field = 'email';
                }
                $user = M('users')->where("email", $username)->whereOr('mobile', $username)->find();
                if ($user) {
                    session('find_password', array('user_id' => $user['user_id'], 'username' => $username,
                        'email' => $user['email'], 'mobile' => $user['mobile'], 'type' => $field));
                    header("Location: " . U('User/find_pwd'));
                    exit;
                } else {
                    $this->error("用户名不存在，请检查");
                }
            }
        }
        return $this->fetch();
    }

    function find_pwd()
    {
        if ($this->user_id > 0) {
            header("Location: " . U('User/Index'));
        }
        $user = session('find_password');
        if (empty($user)) {
            $this->error("请先验证用户名", U('User/forget_pwd'));
        }
        $this->assign('user', $user);
        return $this->fetch();
    }


    public function set_pwd()
    {
        if ($this->user_id > 0) {
//            header("Location: " . U('User/Index'));
            $this->redirect('Mobile/User/Index');
        }
        $check = session('validate_code');
        if (empty($check)) {
            header("Location:" . U('User/forget_pwd'));
        } elseif ($check['is_check'] == 0) {
            $this->error('验证码还未验证通过', U('User/forget_pwd'));
        }
        if (IS_POST) {
            $password = I('post.password');
            $password2 = I('post.password2');
            if ($password2 != $password) {
                $this->error('两次密码不一致', U('User/forget_pwd'));
            }
            if ($check['is_check'] == 1) {
                //$user = get_user_info($check['sender'],1);
                $user = M('users')->where("mobile", $check['sender'])->whereOr('email', $check['sender'])->find();
                M('users')->where("user_id", $user['user_id'])->save(array('password' => encrypt($password)));
                session('validate_code', null);
                //header("Location:".U('User/set_pwd',array('is_set'=>1)));
                $this->success('新密码已设置行牢记新密码', U('User/index'));
                exit;
            } else {
                $this->error('验证码还未验证通过', U('User/forget_pwd'));
            }
        }
        $is_set = I('is_set', 0);
        $this->assign('is_set', $is_set);
        return $this->fetch();
    }

    //发送验证码
    public function send_validate_code()
    {
        $type = I('type');
        $send = I('send');
        $logic = new UsersLogic();
        $res = $logic->send_validate_code($send, $type);
        $this->ajaxReturn($res);

    }

    public function check_validate_code()
    {
        $code = I('post.code');
        $send = I('send');
        $logic = new UsersLogic();
        $res = $logic->check_validate_code($code, $send);
        $this->ajaxReturn($res);
    }

    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id)
    {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            $this->error("验证码错误");
        }
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'user_login';
        $config = array(
            'fontSize' => 40,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }

    /**
     * 账户管理
     */
    public function accountManage()
    {
        return $this->fetch();
    }

    /**
     * 确定收货成功
     */
    public function order_confirm()
    {
        $id = I('get.id/d', 0);
        $data = confirm_order($id, $this->user_id);
        if (!$data['status']) {
            $this->error($data['msg']);
        } else {
            $model = new UsersLogic();
            $order_goods = $model->get_order_goods($id);            
            $this->assign('order_goods', $order_goods);
            return $this->fetch();
            exit;
        }
    }

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $order_id = I('order_id/d', 0);
        $order_sn = I('order_sn', 0);
        $goods_id = I('goods_id/d', 0);
        $good_number = I('good_number', 0); //申请数量
        $spec_key = I('spec_key');
        $c = M('order')->where(['order_id' => $order_id, 'user_id' => $this->user_id])->count();
        if ($c == 0) {
            $this->error('非法操作');
            exit;
        }

        $return_goods = M('return_goods')
            ->where(['order_id' => $order_id, 'goods_id' => $goods_id, 'spec_key' => $spec_key])
            ->find();
        if (!empty($return_goods)) {
            $this->success('已经提交过退货申请!', U('Mobile/User/return_goods_info', array('id' => $return_goods['id'])));
            exit;
        }
        if (IS_POST) {
            // 晒图片
            if (count($_FILES['return_imgs']['tmp_name'])>0) {
                $files = request()->file('return_imgs');
                $save_url = 'public/upload/return_goods/' . date('Y', time()) . '/' . date('m-d', time());
                foreach ($files as $file) {
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->rule('uniqid')->validate(['size' => 1024 * 1024 * 3, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
                    if ($info) {
                        // 成功上传后 获取上传信息
                        $return_imgs[] = '/'.$save_url . '/' . $info->getFilename();
                    } else {
                        // 上传失败获取错误信息
                        $this->error($file->getError());
                    }
                }
                if (!empty($return_imgs)) {
                    $data['imgs'] = implode(',', $return_imgs);
                }
            }
            $data['order_id'] = $order_id;
            $data['order_sn'] = $order_sn;
            $data['goods_id'] = $goods_id;
            $data['addtime'] = time();
            $data['user_id'] = $this->user_id;
            $data['type'] = I('type'); // 服务类型  退货 或者 换货
            $data['reason'] = I('reason'); // 问题描述     
            $data['spec_key'] = I('spec_key'); // 商品规格						       
            $res = M('return_goods')->add($data);
            $data['return_id'] = $res;  //退换货id
            $this->assign('data',$data);
            return $this->fetch('return_good_success'); //申请成功
//            $this->success('申请成功,客服第一时间会帮你处理', U('Mobile/User/order_list'));
            exit;
        }

//        $goods = M('goods')->where("goods_id", $goods_id)->find();
        $goods = M('order_goods')->where("goods_id", $goods_id)->find();
        //查找订单收货地址
        $region = M('order')->field('consignee,country,province,city,district,twon,address,mobile')->where("order_id = $order_id")->find();
        $region_list = get_region_list();
        $this->assign('region_list', $region_list);
        $this->assign('region', $region);
        $this->assign('goods', $goods);
        $this->assign('order_id', $order_id);
        $this->assign('order_sn', $order_sn);
        $this->assign('goods_id', $goods_id);

        return $this->fetch();
    }

    /**
     * 退换货列表
     */
    public function return_goods_list()
    {
        //退换货商品信息
        $count = M('return_goods')->where("user_id", $this->user_id)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('return_goods')->where("user_id", $this->user_id)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');  //获取商品ID
        if (!empty($goods_id_arr)){
            $goodsList = M('goods')->where("goods_id", "in", implode(',', $goods_id_arr))->getField('goods_id,goods_name');
        }

        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('page', $page->show());// 赋值分页输出
        if (I('is_ajax')) {
            return $this->fetch('ajax_return_goods_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id', 0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        if ($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();
        $this->assign('goods', $goods);
        $this->assign('return_goods', $return_goods);
        return $this->fetch();
    }


    public function recharge()
    {
        $order_id = I('order_id/d');
        $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        $bank_img = include APP_PATH . 'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);

        if ($order_id > 0) {
            $order = M('recharge')->where("order_id", $order_id)->find();
            $this->assign('order', $order);
        }
        return $this->fetch();
    }

    /**
     * 申请提现记录
     */
    public function withdrawals()
    {
        C('TOKEN_ON', true);
        if (IS_POST) {
        	$userinfo = M('users')->where(array('user_id'=>$this->user_id))->find();
        	if($userinfo['is_lock'] == 1){
        		echo json_encode(array('code'=>-1,'msg'=>'该账户已被封号，资金冻结，不可提现！'));
        		exit;
        	}
            //$this->verifyHandle('withdrawals');
            $data = I('post.');
            $data['user_id'] = $this->user_id;
            //判断数据有效性
            if(!$data['money'] && !$data['account_bank']){
                echo json_encode(array('code'=>-1,'msg'=>'请填写正确信息'));
                exit;
            }
            if($data['money'] < 0){
            	echo json_encode(array('code'=>-1,'msg'=>'提现金额不能是负数'));
                exit;
            }
            $data['create_time'] = time();
            $distribut_min = tpCache('basic.min'); // 最少提现额度
            if ($data['money'] < $distribut_min) {
                echo json_encode(array('code'=>-1,'msg'=>'每次最少提现额度'.$distribut_min));
                exit;
            }
            if ($data['money'] > $this->user['user_money']) {
                echo json_encode(array('code'=>-1,'msg'=>"你最多可提现{$this->user['user_money']}账户余额"));
                exit;
            }
            $withdrawal = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');
            if ($this->user['user_money'] < ($withdrawal + $data['money'])) {
                echo json_encode(array('code'=>-1,'msg'=>'您有提现申请待处理，本次提现余额不足'));
                exit;
            }
            if (M('withdrawals')->add($data)) {
                echo json_encode(array('code'=>-1,'msg'=>'已提交申请！'));
                exit;
            } else {
            	echo json_encode(array('code'=>-1,'msg'=>'提交失败,联系客服!'));
                exit;
            }
        }
        $withdrawals_where['user_id'] = $this->user_id;
        $count = M('withdrawals')->where($withdrawals_where)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('withdrawals')->where($withdrawals_where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();

        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list', $list); // 下线
        if (I('is_ajax')) {
            return $this->fetch('ajax_withdrawals_list');
            exit;
        }
        $order_count = M('order')->where("user_id", $this->user_id)->count(); // 我的订单数
        $goods_collect_count = M('goods_collect')->where("user_id", $this->user_id)->count(); // 我的商品收藏
        $comment_count = M('comment')->where("user_id", $this->user_id)->count();//  我的评论数
        $coupon_count = M('coupon_list')->where("uid", $this->user_id)->count(); // 我的优惠券数量
        $level_name = M('user_level')->where("level_id", $this->user['level'])->getField('level_name'); // 等级名称
        $this->assign('level_name', $level_name);
        $this->assign('order_count', $order_count);
        $this->assign('goods_collect_count', $goods_collect_count);
        $this->assign('comment_count', $comment_count);
        $this->assign('coupon_count', $coupon_count);
        $this->assign('user_money', $this->user['user_money']);    //用户余额
        return $this->fetch();
    }

    /**
     * 申请记录列表
     */
    public function withdrawals_detail()
    {
        $withdrawals_where['user_id'] = $this->user_id;
        $count = M('withdrawals')->where($withdrawals_where)->count();
        $page = new Page($count, 10);
        $list = M('withdrawals')->where($withdrawals_where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();

        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list', $list); // 下线
        if (I('is_ajax')) {
            return $this->fetch('ajax_withdrawals_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 删除已取消的订单
     */
    public function order_del()
    {
        $user_id = $this->user_id;
        $order_id = I('get.order_id');
        $order = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        if (empty($order)) {
            return $this->error('订单不存在');
            exit;
        }
        $res = M('order')->where("order_id=$order_id and order_status=3")->delete();
        $result = M('order_goods')->where("order_id=$order_id")->delete();
        if ($res && $result) {
            return $this->success('成功', "mobile/User/order_list");
            exit;
        } else {
            return $this->error('删除失败');
            exit;
        }
    }

    /**
     * 我的关注
     * $author lxl
     * $time   2017/1
     */
    public function myfocus()
    {
        return $this->fetch();
    }

    /**
     * 待收货列表
     * $author lxl
     * $time   2017/1
     */
    public function wait_receive()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
        if (I('type') == 'WAITRECEIVE') {
            $where .= C(strtoupper(I('type')));
        }
        $count = M('order')->where($where)->count();
        $pagesize = C('PAGESIZE');
        $Page = new Page($count, $pagesize);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }

        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
            //订单物流单号
            $invoice_no = M('DeliveryDoc')->where("order_id", $value['order_id'])->getField('invoice_no', true);
            $order_list[$key][invoice_no] = implode(' , ', $invoice_no);
        }
        $this->assign('page', $show);
        $this->assign('order_list', $order_list);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_wait_receive');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  用户消息通知
     * @author dyr
     * @time 2016/09/01
     */
    public function message_notice()
    {
        return $this->fetch('user/message_notice');
    }

    /**
     * ajax用户消息通知请求
     * @author dyr
     * @time 2016/09/01
     */
    public function ajax_message_notice()
    {
        $type = I('type', 0);
        $user_logic = new UsersLogic();
        $message_model = new Message();
        if ($type == 1) {
            //系统消息
            $user_sys_message = $message_model->getUserMessageNotice();
            $user_logic->setSysMessageForRead();
        } else if ($type == 2) {
            //活动消息：后续开发
            $user_sys_message = array();
        } else {
            //全部消息：后续完善
            $user_sys_message = $message_model->getUserMessageNotice();
        }
        $this->assign('messages', $user_sys_message);
        return $this->fetch('user/ajax_message_notice');

    }

    /**
     * 设置消息通知
     */
    public function set_notice(){
        //暂无数据
        return $this->fetch();
    }
    
    
    /*
     * 窖藏订单列表
     */
    public function cellar_list()
    {
        //我的藏酒列表
        $cellar_list = M('order_goods')
                     ->alias('a')
                     ->join('order b','a.order_id = b.order_id')
                     ->join('cellar_goods_attr c','a.goods_id = c.goods_id')
                     ->join('goods e','e.goods_id = a.goods_id')
                     ->join('cellar_type ct','ct.id = c.type_id')
                     ->join('cellar_aroma ca','ca.id = c.aroma_id')
                     ->join('cellar_theme cth','cth.id = c.theme_id')
                     ->join('suppliers d','c.winery_id = d.suppliers_id')
                     ->where('b.user_id = '.$this->user_id.' and e.type = 1')
                     ->field('a.*,b.*,d.suppliers_name,ct.title as cellar_type,ca.title as cellar_aroma,cth.title as cellar_theme,e.original_img,e.shop_price')
                     ->order("b.add_time desc")
                     ->select();
        foreach ($cellar_list as $key=>$value){
            $cellar_list[$key]['other_content'] = json_decode($value['other_content'],true);
        }
        //我收到的藏酒
        $recive_list = M('cellar_record')
                        ->alias("cr")
                        ->join("f_users u","cr.from_user_id = u.user_id")
                        ->join('f_order_goods og',"cr.rec_id = og.rec_id")
                        ->join("f_goods g","cr.goods_id = g.goods_id")
                        ->join('cellar_goods_attr c','cr.goods_id = c.goods_id')
                        ->join('cellar_type ct','ct.id = c.type_id')
                        ->join('cellar_aroma ca','ca.id = c.aroma_id')
                        ->join('cellar_theme cth','cth.id = c.theme_id')
                        ->where("cr.to_user_id =".$this->user_id)
                        ->field("cr.*,u.nickname,u.mobile,g.goods_name,g.original_img,g.shop_price,ct.title as cellar_type,ca.title as cellar_aroma,cth.title as cellar_theme,og.other_content")
                        ->order("cr.addtime desc")
                        ->select();
        foreach ($recive_list as $key=>$value){
            $recive_list[$key]['other_content'] = json_decode($value['other_content'],true);
        }
        $this->assign('recive_list',$recive_list);
        $this->assign('cellar_list',$cellar_list);
        return $this->fetch();
    }
    
    
    /*
     * 分销
     */
    function distribut(){
    	
    	$income = get_distribut_income($this->user_id);
    	$this->assign('income',$income);
    	return $this->fetch();
    }
    
    /*
     * 分销二维码
     */
    function distribut_qr(){    
//         $redirect_uri = urlencode("http://www.fengtantianxia.com/Mobile/Index/index/type/distribut/uid/".$this->user_id);
//         $wxurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx344664062a52da42&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect';
//         $state = $this->user_id;
//         $imgurl = getQRCode($wxurl,$state);
//         //统计下线分销商人数
//         $subordinateCount = M('users')->where("first_leader",$this->user_id)->count();
//         $this-> assign('subordinateCount',$subordinateCount);
//         $this-> assign('imgurl',$imgurl);
//     	return $this->fetch();
        if(file_exists("./public/dist/qrcode/".$this->user_id.".png")){
            $imgurl = "./public/dist/qrcode/".$this->user_id.".png";
        }else{
            $accesstoken = getWx_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$accesstoken;
            $data['action_name'] = "QR_LIMIT_STR_SCENE";
            $data['action_info'] = array('scene'=>array("scene_str"=>$this->user_id));
            $result = json_decode(api_notice_increment($url,json_encode($data)),"true");
            $imgurl = "";
            if($result['ticket']){
                $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".UrlEncode($result['ticket']);
                $result = file_get_contents($url);
                $imgurl = "./public/dist/qrcode/";
                if(!file_exists($imgurl)){
                    mkdir($imgurl);
                }
                $imgurl .= $this->user_id.".png";
                $s =file_put_contents($imgurl,$result);
            }
        }
        //统计下线分销商人数
         $subordinateCount = M('users')->where("first_leader =$this->user_id")->count();

        $user = M('users')->where('user_id',$this->user_id)->find();
        $user['head_pic'] = empty($user['head_pic'])?'/public/upload/user/headPic/defaultheadpic.png':$user['head_pic'];
        $this->assign('user',$user);
        $this-> assign('subordinateCount',$subordinateCount);
        $this-> assign('imgurl',$imgurl);
        return $this->fetch();
    }
    
       
    /*
     * 我的分销明细
     */
    public function distribut_list(){
    	
    	$dis_users = M('users')->where('first_leader',$this->user_id)->select();
    	foreach($dis_users as $key=>$val){
    		$distribut_income = get_distribut_income($val['user_id']);
    		$dis_users[$key]['income'] = sprintf("%.2f",$distribut_income['mycost']*0.06);
    	}
    	//print_r($dis_users);
    	$this->assign('dis_users',$dis_users);
    	return $this->fetch();
    }
    
    
    /*
     * 下线的分销明细
     */
    public function distribut_list2(){
    	
    	$user_id = I('get.user_id');
    	if(!empty($user_id)){
    		$dis_users = M('users')->where('first_leader',$user_id)->select();
	    	foreach($dis_users as $key=>$val){
	    		$distribut_income = get_distribut_income($val['user_id']);	    		
	    		$dis_users[$key]['income'] = sprintf("%.2f",$distribut_income['mycost']*0.06);
	    	}
    	}
    	else{
    		$errs = '参数错误，请不要非法操作！';
    	}
    	$dis_users = empty($dis_users)?'暂无下线人员':$dis_users;
    	$this->assign('dis_users',$dis_users);
    	$this->assign('errs',$errs);
    	return $this->fetch();
    }
    
    /*
     * 分销人数统计
     */
    public function distribut_count(){
         
        $user_id = $this->user_id;
        if(!empty($user_id)){
            //查询所有下线
            $dis_users = M('users')->where('first_leader',$user_id)->order("user_id desc")->select();
            //下线人数
            $dis_users_count = count($dis_users);
            //查询今日新增下线
            $today = strtotime(date('Y-m-d', time()));//今天0是时间戳
            $end = $today + 24 * 60 * 60;//今天24点的是时间戳
            $dis_today = M('users')->where("first_leader=$user_id and reg_time > $today and reg_time < $end")->select();
            //今日下线人数
            $dis_today_count = count($dis_today);
            
            //查询已绑定手机人数
            $dis_sy_users = M('users')->where(array('first_leader'=>$user_id,'mobile_validated'=>1))->order("user_id desc")->select();
            //下线已绑定手机人数
            $dis_sy_count = count($dis_sy_users);
        }
        else{
            $errs = '参数错误，请不要非法操作！';
        }
        $dis_users = empty($dis_users)?0:$dis_users;
        $this->assign('dis_users',$dis_users);
        $this->assign('dis_today',$dis_today);
        $this->assign('dis_users_count',$dis_users_count);
        $this->assign('dis_today_count',$dis_today_count);
        $this->assign('dis_sy_count',$dis_sy_count);
        $this->assign('errs',$errs);
        $this->assign('user_id',sprintf('%09d',$user_id));
        return $this->fetch();
    }
    
    /*
     * 我的钱包
     */
    function wallet(){
    	cookie('m',false);
    	$user = M('users')->where('user_id',$this->user_id)->find();
    	$from_red_pac = Session::pull('from_red_pac');//针对抢红包活动判断返回首页路径
    	if($from_red_pac){
    		$controller_name = Session::get('controller_name');
    	    $this->assign('baseurl',U('/Mobile/'.$controller_name));	
    	}
        $this->assign('user',$user);
    	return $this->fetch();
    }
    
    
  /**yuankun**/
    /*
     * 订单列表
     */
    public function destine_list()
    {
        $destine_list = M('order_goods')
        ->alias('a')
        ->join('order b','a.order_id = b.order_id')
        ->join('goods e','e.goods_id = a.goods_id')
        ->join("destine_goods_attr dga","dga.goods_id = e.goods_id")
        ->join('suppliers d','dga.winery_id = d.suppliers_id')
        ->where('b.user_id = '.$this->user_id.' and e.type = 2')
        ->order('a.goods_id DESC')
        ->select();
        foreach ($destine_list as $key=>$value){
            $destine_list[$key]["other_content"] = json_decode($value["other_content"],"true");
        }
        $this->assign('destine_list',$destine_list);
        return $this->fetch();
    }
    
    //定制预览
    public function  destine_preview(){
        $rec_id = I("post.id");
        $goosinfo = M("order_goods")->where("rec_id",$rec_id)->find();
        $goosinfo['other_content'] = json_decode($goosinfo['other_content'],"true");
        $otherContent = $goosinfo['other_content'];
        $otherContent['despic'] = empty($goosinfo['other_content']['despic'])?"/public/upload/destine/0_1489368120.png":$goosinfo['other_content']['despic'];
        $otherContent['message'] = empty($goosinfo['other_content']['message'])?"":$goosinfo['other_content']['message'];
        //格式化图片路径
        if(substr($otherContent['despic'],0,1) == "."){
            $otherContent['despic'] = substr($otherContent['despic'],1);
        }
        if($goosinfo['other_content']['destine_status'] < 1){
            $otherContent['destine_status'] = 0;
        }
        $goosinfo['other_content'] = $otherContent;
        $data['other_content'] = json_encode($otherContent);
        M("order_goods")->where("rec_id",$rec_id)->save($data);
        if(!empty($goosinfo['other_content']['workspic'])){  //取最新的设计图
            $goosinfo['other_content']['worksLast'] = end($goosinfo['other_content']['workspic']);
        }else{
            $goosinfo['other_content']['worksLast'] = $goosinfo['other_content']['despic'];
        }
        $this->assign("goosinfo",$goosinfo);
        return $this->fetch();
    }
    
    //定制确认
    public function destine_sign(){
        $rec_id = I("post.rec_id");
        $sign = I("post.sign");
        $goosinfo = M("order_goods")->where("rec_id",$rec_id)->find();
        $otherContent = json_decode($goosinfo['other_content'],"true");
        $otherContent['sign'] = $sign;
        $otherContent['destine_status'] = 2;//客户确认完成
        $data['other_content'] = json_encode($otherContent);
        $result = M("order_goods")->where("rec_id",$rec_id)->save($data);
        if($result){
            $back['status'] = 1;
            $back['msg'] = "操作成功";
            $back['data'] = $result;
        }else{
            $back['status'] = 0;
            $back['msg'] = "操作失败";
            $back['data'] = "记录插入失败";
        }
        echo json_encode($back);
        exit();
    }
    
    //赠酒
    public function cellar_give(){
        $rec_id = I("get.id");
        $date = $this->getOrderInfo($rec_id);
        $this->assign("order_goodsinfo",$date['order_goodsinfo']);
        $this->assign("orderinfo",$date['orderinfo']);
        return $this->fetch();
    }
    
    
    //ajax查询用户是否存在
    public function checkUserExit(){
        if (IS_AJAX){
            $phone = I("post.phone");
            if(empty($phone)){
                echo 0;
                exit();
            }
            $result = M('users')->where('mobile',$phone)->find();
            if ($result){
                echo json_encode($result);
            }else{
                echo 0;
            }
            exit();
        }
    }
    
    
    //提酒
    public function cellar_extract(){
        if(I('get.type') == 1){//提酒藏酒
            $rec_id = I("get.id");
            //取得订单及订单详情
            $date = $this->getOrderInfo($rec_id); 
        }elseif(I('get.type') == 2){//提酒赠送的酒
            $id = I("get.id");
            $date['order_goodsinfo'] = M('cellar_record')->where('id',$id)->find();
            //踢除已提取的藏酒
            $recordlist = M("cellar_record")->where('to_user_id',$id)->select();
            $date['order_goodsinfo']['bottle_num'] = explode(",",$date['order_goodsinfo']['bottle_num']);
            $list = array();
            foreach ($recordlist as $value){
                if((!empty($value['order_info']))){
                    //组合已操作藏酒编号  0 => '待确认', 1 => '已确认',2 => '已收货', 4 => '已完成',
                    if(in_array(json_decode($value['order_info'],"true")['order_status'],array(0,1,2,4))){
                        $list = array_merge($list,explode(",",$value['bottle_num']));
                    }
                }
            }
            $date['order_goodsinfo']['bottle_num'] = array_diff($date['order_goodsinfo']['bottle_num'],$list);
        }
        //获取用户默认地址
        $address = M("user_address")->where(array("user_id"=>$this->user_id,"is_default"=>1))->find();
        //获取快递列表
        $shippingList = M('plugin')->where(array("type"=>"shipping","status"=>"1"))->select();
        $this->assign("shippingList",$shippingList);
        $this->assign("address",$address);
        $this->assign("type",I('get.type'));
        $this->assign("order_goodsinfo",$date['order_goodsinfo']);
        $this->assign("orderinfo",$date['orderinfo']);
        return $this->fetch();
    }
    
    
    //查询订单级订单详情
    public function  getOrderInfo($rec_id){
        $result['order_goodsinfo'] = M('order_goods')->where("rec_id",$rec_id)->find();
        $result['orderinfo'] = M("order")->where("order_id",$result['order_goodsinfo']['order_id'])->find();
        $result['order_goodsinfo']['bottle_num'] = explode(",",$result['order_goodsinfo']['bottle_num']);
        $list = array();
        //获取可操作的藏酒信息
        $recordlist = M("cellar_record")->where("order_id",$result['order_goodsinfo']['order_id'])->select();
        foreach ($recordlist as $value){
            if((!empty($value['order_info']))){
                //组合已操作藏酒编号  0 => '待确认', 1 => '已确认',2 => '已收货', 4 => '已完成',
                if(in_array(json_decode($value['order_info'],"true")['order_status'],array(0,1,2,4))){
                    $list = array_merge($list,explode(",",$value['bottle_num']));
                }
            }
            if ($value['types']){//赠酒记录
                $list = array_merge($list,explode(",",$value['bottle_num']));
            }
        }
        //将已操作过的藏酒剔除
        $result['order_goodsinfo']['bottle_num'] = array_diff($result['order_goodsinfo']['bottle_num'],$list);
        //合并所有的操作记录
//         $result['order_goodsinfo']['bottle_num'] = array(2131,5433,54651,54654);
        return $result;
    }
    
    //藏酒自提确定
    public function  cellar_ziti(){
        if(I('post.type') == 1){
            $date = $this->getOrderInfo($_POST['rec_id']);
        }else{
            $date['order_goodsinfo'] =  M('cellar_record')->where('id',$_POST['id'])->find();
        }
        $date['order_goodsinfo']['consignee'] = $_POST['consignee'];
        $date['order_goodsinfo']['phone'] = $_POST['phone'];
        $date['order_goodsinfo']['extractDate'] = $_POST['extractDate'];
        $date['order_goodsinfo']['date'] = strtotime($_POST['extractDate']);
        $date['order_goodsinfo']['bottle_num'] = explode(",",$_POST['bottle_num']);//选中的藏酒
        $date['order_goodsinfo']['bottle_num1'] = $_POST['bottle_num'];//选中的藏酒
        $date['order_goodsinfo']['num'] = count($date['order_goodsinfo']['bottle_num']);//选中的藏酒
        $this->assign("user_id",$this->user_id);
        $this->assign("type",I('post.type'));
        $this->assign("id",empty($date['order_goodsinfo']['id'])?0:$date['order_goodsinfo']['id']);//id不存在时传空字符，防止前台模板取值报错
        $this->assign("order_goodsinfo",$date['order_goodsinfo']);
        $this->assign("orderinfo",$date['orderinfo']);
        return $this->fetch();
    }
    
    //藏酒配送确定
    public function  cellar_peisong(){
        if(I("post.type") == 1)
        {
            $date = $this->getOrderInfo($_POST['rec_id']);
        }elseif (I("post.type") == 2){
            $date['order_goodsinfo'] =  M('cellar_record')->where('id',$_POST['id'])->find();
        }
        $date['order_goodsinfo']['bottle_num'] = explode(",",$_POST['bottle_num']);//选中的藏酒
        $date['order_goodsinfo']['bottle_num1'] = $_POST['bottle_num'];//选中的藏酒
        $date['order_goodsinfo']['num'] = count($date['order_goodsinfo']['bottle_num']);//选中的藏酒
        //获取用户默认地址
        $address = M("user_address")->where(array("user_id"=>$this->user_id,"is_default"=>1))->find();
        //获取快递列表
        $shippingList = M('plugin')->where(array("type"=>"shipping","status"=>"1"))->select();
        //获取商品信息
        $goodInfo =  M("goods")->alias("g")
                        ->join("f_cellar_goods_attr cga","cga.goods_id = g.goods_id")
                        ->join("f_cellar_aroma ca","ca.id = cga.aroma_id","left")
                        ->join("f_cellar_theme ct","ct.id = cga.theme_id","left")
                        ->join("f_cellar_type cty","cty.id = cga.type_id","left")
                        ->join("f_suppliers s","s.suppliers_id = cga.winery_id","left")
                        ->where("g.goods_id",$date['order_goodsinfo']['goods_id'])
                        ->field("g.*,ca.title as aroma,ct.title as theme,cty.title as type,s.suppliers_name")
                        ->find();
//         var_dump($goodInfo);
        $this->assign("type",I("post.type"));
        $this->assign("user_id",$this->user_id);
        $this->assign("goodinfo",$goodInfo);
        $this->assign("shippingList",$shippingList);
        $this->assign("address",$address);
        $this->assign("id",empty($date['order_goodsinfo']['id'])?0:$date['order_goodsinfo']['id']);//id不存在时传空字符，防止前台模板取值报错
        $this->assign("order_goodsinfo",$date['order_goodsinfo']);
        $this->assign("orderinfo",$date['orderinfo']);
        return $this->fetch();
    }
    //藏酒提取配送支付成功
    public function cellar_peisong_success(){
        $id = I('get.id');
        $recordinfo = M('cellar_record')->where('id',$id)->find();
        $recordinfo['order_info'] = json_decode($recordinfo['order_info'],true);
        $recordinfo['order_action'] = json_decode($recordinfo['order_action'],true);
        //增加订单日志
        $data1['pay_status'] = $recordinfo['order_info']['pay_status'];
        $data1['order_status'] = $recordinfo['order_info']['order_status'];
        $data1['action_user'] = $this->user_id;
        $data1['action_note'] = "用户已支付成功";
        $data1['log_time'] = time();
        $data1['status_desc'] = "申请提酒支付";
        $recordinfo['order_action'][] = $data1;
        $data2['order_action'] = json_encode($recordinfo['order_action']);
        M('cellar_record')->where('id',$id)->save($data2);
        //修改订单状态
        $recordinfo['order_info']['pay_status'] = 1;
        $recordinfo['order_info']['pay_time'] = time();
        $data['order_info'] = json_encode($recordinfo['order_info']);
        $result = M('cellar_record')->where('id',$id)->save($data);
        if($result){
            $this->success("提酒申请,支付成功","/Mobile/User/cellar_info/id/".$recordinfo['rec_id']);
        }else{
            $this->error("无效操作");
        }
    }
    
    /*
     * 藏酒操作
     */
    public function cellar_oprate(){   
        //数据整合
        $date['order_id'] = I('post.order_id');
        $date['rec_id'] = I('post.rec_id');
        $date['goods_id'] = I('post.goods_id');
        $date['num'] = I('post.num');
        $date['addtime'] = time();
        $date['types'] = I('post.types');
        $date['bottle_num'] = $_POST['bottle_num'];//I获取数组变量，ajax返回报错
        $date['from_user_id'] = I('post.from_user_id');
        $date['to_user_id'] = I('post.to_user_id');
        if(I('post.types')){//赠酒
            $date['order_info'] = json_encode(array('msg'=>I('post.msg')));
        }else{//提酒
            $orderinfo['extract_type'] = I('post.extract_type');
            if (I('post.extract_type')){//自提
                $orderinfo['consignee'] = I('post.consignee');
                $orderinfo['phone'] = I('post.phone');
                $orderinfo['date'] = I('post.date');
                $orderinfo['shipping_code'] = 0;
                $orderinfo['shipping_price'] = 0;
                $orderinfo['shipping_name'] = 0;
            }else{//配送
                $date['address_id'] = I('post.address_id');
                $orderinfo['shipping_code'] = I('post.shipping_code');
                $orderinfo['shipping_price'] = I('post.shipping_price');
                $orderinfo['shipping_name'] = I('post.shipping_name');
            }
            //生成提取订单信息
            $orderinfo['order_sn'] = "TJ".getOrdersn();
//             $back['status'] = 0;//记录插入失败
//             $back['msg'] = $orderinfo;
//             echo json_encode($back);
//             exit();
            $orderinfo['order_status'] = 0;//已申请
            $orderinfo['pay_status'] = 0;//未支付
            $orderinfo['pay_time'] = 0;//初始化支付时间
            $orderinfo['pay_code'] = 0;//初始化支付方式
            
            //生成订单操作信息
            $orderaction[0]['pay_status'] = $orderinfo['pay_status'];
            $orderaction[0]['order_status'] = $orderinfo['order_status'];
            $orderaction[0]['action_user'] = I('post.from_user_id');
            $orderaction[0]['action_note'] = "您已申请提酒，请等待商家发货";
            $orderaction[0]['log_time'] = time();
            $orderaction[0]['status_desc'] = "申请提酒";
            $date['order_info'] = json_encode($orderinfo);
            $date['order_action'] = json_encode($orderaction);
        }
        //将操作添加到藏酒记录表
        $recordid = M("cellar_record")->add($date);
        if(empty($recordid)){
            $back['status'] = 0;//记录插入失败
            $back['msg'] = "操作失败请重试";
            $back['data'] = "记录插入失败";
        }else{
            $back['status'] = 1;//记录插入失败
            $back['msg'] = "操作成功";
            $back['data'] = $recordid;
        }
        echo json_encode($back);
        exit();
    }
    
    //提取藏酒支付页面
    public function surePay(){
        $id = I("get.id");
        //获取提酒信息
        $recordinfo = M("cellar_record")->where("id",$id)->find();
        $recordinfo['order_info'] = json_decode($recordinfo['order_info'],"true");
        //获取支付方式
         $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');
        
        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        $bank_img = include APP_PATH . 'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);
        $this->assign("recordinfo",$recordinfo);
        return $this->fetch();
    }
   
    
    
    //藏酒详情
    public function cellar_info() {
        if(I("get.type") == 1){//我的藏酒详情
            $rec_id = I("get.id");
            //获取商品详情信息
            $goodsInfo = M("order_goods")
            ->alias("og")
            ->join("f_goods g","g.goods_id = og.goods_id")
            ->join("f_cellar_goods_attr cga", "og.goods_id=cga.goods_id")
            ->join("f_suppliers s","cga.winery_id = s.suppliers_id")
            ->join("f_cellar_theme ct","ct.id = cga.theme_id")
            ->join("f_cellar_type cty","cty.id =cga.type_id")
            ->join("f_cellar_aroma ca","ca.id = cga.aroma_id")
            ->join("f_order od","od.order_id = og.order_id")
            ->where("og.rec_id",$rec_id)
            ->field("og.*,s.suppliers_name,ct.title as themetitle,cty.title as typetitle,ca.title as aromatitle,od.add_time,g.shop_price,g.original_img")
            ->find();
           
            $years = M('cellar_year_record')->where(array('rec_id'=>$rec_id,'user_id'=>$this->user_id,'type'=>0,'pay_status'=>1))->sum("years");
            //获取商品原产地
            //获取赠酒记录
            $cellarGive = M("cellar_record")->where(array("order_id"=>$goodsInfo['order_id'],"goods_id"=>$goodsInfo['goods_id'],"types"=>1))->select();
            //获取提酒记录
            $cellarExtract = M("cellar_record")->where(array("order_id"=>$goodsInfo['order_id'],"goods_id"=>$goodsInfo['goods_id'],"types"=>0))->select();
            $this->assign("cellarGive",$cellarGive);
        }elseif(I("get.type") == 2){//我的收酒详情
            //收酒提取记录
            $id = I("get.id");
            $goodsInfo = M('cellar_record')
            ->alias("cr")
            ->join("f_order_goods og","cr.rec_id = og.rec_id")
            ->join("f_goods g","g.goods_id = og.goods_id")
            ->join("f_cellar_goods_attr cga", "og.goods_id=cga.goods_id")
            ->join("f_suppliers s","cga.winery_id = s.suppliers_id")
            ->join("f_cellar_theme ct","ct.id = cga.theme_id")
            ->join("f_cellar_type cty","cty.id =cga.type_id")
            ->join("f_cellar_aroma ca","ca.id = cga.aroma_id")
            ->join("f_order od","od.order_id = og.order_id")
            ->where("cr.id",$id)
            ->field("cr.*,g.goods_name,g.original_img,s.suppliers_name,ct.title as themetitle,cty.title as typetitle,ca.title as aromatitle,od.add_time,g.shop_price,og.other_content")
            ->find();
            //续费年限
            $years = M('cellar_year_record')->where(array('rec_id'=>$id,'user_id'=>$this->user_id,'type'=>1,'pay_status'=>1))->sum("years");
            //提酒记录
            $cellarExtract = M('cellar_record')->where(array("rec_id"=>$goodsInfo['rec_id'],"to_user_id"=>$id,"from_user_id"=>$this->user_id))->select();
        }  
       
        $goodsInfo['other_content'] = json_decode($goodsInfo['other_content'],true);
        $goodsInfo['bottle_num'] = explode(",",$goodsInfo['bottle_num']);
        $goodsInfo['end_time'] = strtotime("+".($goodsInfo['other_content']['cellar_years']+$years)." years",$goodsInfo['add_time']);
        $this->assign("cellarExtract",$cellarExtract);
        $this->assign("cellar_years",$years+$goodsInfo['other_content']['cellar_years']);
        $this->assign("type",I("get.type"));
        $this->assign("goodsInfo",$goodsInfo);
        return $this->fetch();
    }
    
    //延长收货
    public function cellar_years_add(){
        if(I("type")){
            $id =  I("id");
            $cellar_info = M('cellar_record')
                            ->alias("cr")
                            ->join("f_order_goods og","cr.rec_id = og.rec_id")
                            ->where("cr.id",$id)
                            ->field("cr.*,og.other_content")
                            ->find();
            
            //获取剩余藏酒数量
            $sends_cellar_count = M('cellar_record')->where("to_user_id",$cellar_info['id'])->select();
           
        }else{
            $rec_id = I("id");
            $cellar_info = M('order_goods')
                            ->alias("g")
                            ->join("f_order o","g.order_id = o.order_id")
                            ->where("g.rec_id",$rec_id) 
                            ->field("g.*,o.add_time")
                            ->find();
            
            //获取藏酒剩余数量
            $sends_cellar_count = M('cellar_record')->where(array("rec_id"=>$rec_id,"from_user_id"=>$this->user_id))->select();
//             $residue = $cellar_info['goods_num'] - $sends_cellar_count;
        }
        $list = array();
        foreach ($sends_cellar_count as $value){
            if((!empty($value['order_info']))){
                //组合已操作藏酒编号  0 => '待确认', 1 => '已确认',2 => '已收货', 4 => '已完成',
                if(in_array(json_decode($value['order_info'],"true")['order_status'],array(0,1,2,4))){
                    $list = array_merge($list,explode(",",$value['bottle_num']));
                }
            }
            if ($value['types']){//赠酒记录
                $list = array_merge($list,explode(",",$value['bottle_num']));
            }
        }
       
        //将已操作过的藏酒剔除
        $cellar_info['bottle_num'] = explode(",",$cellar_info['bottle_num']);

        $cellar_info['bottle_num'] = array_diff($cellar_info['bottle_num'],$list);

        //剩余可操作酒的数量
        $residue = count($cellar_info['bottle_num']);
        $cellar_info['other_content'] = json_decode($cellar_info['other_content'],true);
        if($residue > 0){
            //获取剩余重量
            $unit = str_replace("L/坛","",$cellar_info['other_content']['capacity']);
            $residue_weight = $residue*$unit;
        }else{
            $this->error("您的藏酒已取完",U("/mobile/user/cellar_list"));
        }
        $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');
        
        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        
        $bank_img = include APP_PATH . 'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);
        $this->assign('residue_weight',$residue_weight);
        $this->assign('residue_weight_year',$residue_weight*2);
        $this->assign("rec_id",$rec_id);
        $this->assign('type',I("type"));
        $this->assign('id',$id);
        return $this->fetch();
    }
    //藏酒延长时间付款成功
    public function cellar_years_add_success(){
//         $rec_id = I("get.id");
        $order_id = I("get.order_id");
        $cellar_year_record = M('cellar_year_record')->where('order_id',$order_id)->find();
        $data['pay_time'] = time();
        $data['pay_status'] = 1;
        //修改支付记录
        $result = M('cellar_year_record')->where('order_id',$order_id)->save($data);
        if($result){
            $this->success("付款成功","/Mobile/User/cellar_list");
        }else{
            $this->error('无效修改');
        }
    }
    
    //查看藏酒操作详情
    public function  cellar_recordInfo(){
        $id = I("post.id");
        $recordInfo = M("cellar_record")
        ->alias("r")
        ->join("f_users u","r.to_user_id = u.user_id","left")
        ->join("f_user_address ua","ua.address_id = r.address_id","left")
        ->where("r.id",$id)
        ->field("r.*,u.nickname,ua.consignee,ua.address,ua.mobile,u.mobile as mobile1")
        ->find();
        $recordInfo["order_info"] = json_decode($recordInfo["order_info"],"true");
        $recordInfo["order_action"] = json_decode($recordInfo["order_action"],"true");            
        $recordInfo['bottle_num1'] = explode(',',$recordInfo['bottle_num']);
        $goodsInfo = M("goods")->where("goods_id",$recordInfo['goods_id'])->find();
        $this->assign("goodsInfo",$goodsInfo);
        $this->assign("recordInfo",$recordInfo);
        return $this->fetch();
    }
    
    //藏酒提取取消发货
    public function cellar_cancel(){
        $id = I("post.rec_id");
        if(cellar_order_action("invalid",$id,"取消提酒申请")){
            $back['status'] = 1;
            $back['msg'] = "操作成功";
        }else{
            $back['status'] = 0;
            $back['msg'] = "操作失败";
        }
        echo json_encode($back);
        exit();
    }
    /****yuankun end****/
    
    
    /**
     *  金酒币
     */
    public function gold(){   
        $user = M('users')->where('user_id',$this->user_id)->find();
        if($user['pay_gold'] >= 100){//计算可提现金额
        	$user['pay_gold_TX'] = $user['pay_gold'] * 0.3;
        }
        else{
        	$user['pay_gold_TX'] = 0;
        }
        $user['pay_gold_TX'] = sprintf("%.2f", $user['pay_gold_TX']);
//         $user['pay_gold_TX'] = 30.25;
        $this->assign('user',$user);
        return $this->fetch();
    }
    
    
    /**
     *  金酒币提现
     */
    public function gold_cash(){  
    	$user = M('users')->where('user_id',$this->user_id)->find();
        if($user['pay_gold'] >= 100){//计算可提现金额
        	$user['pay_gold_TX'] = $user['pay_gold'] * 0.3;
        }
        else{
        	$user['pay_gold_TX'] = 0;
        }
        if(IS_POST){
//             判断的那个月是否已提现
            $BeginDate=strtotime(date("Y-m"));
            $endDate = strtotime("+1 month",$BeginDate);
            $gold_cash_record = M("user_income")->where("add_time>$BeginDate and add_time<$endDate and uid =$this->user_id and source_name='金酒币提现'")->find();
            if($gold_cash_record){
                $return_arr = array(
                    'status' => -1,
                    'msg' => '提现失败,您本月已成功提现过',
                    'data' => array('url' => U('Mobile/User/gold')),
                );
                return  $this->ajaxReturn($return_arr);
            }
        	$data = I('post.');
        	$money = empty($data['money'])?0:$data['money'];
        	if($user['pay_gold_TX'] == 0){
        	    $return_arr = array(
        	        'status' => -1,
        	        'msg' => '提现失败,可提现金额大于100才能提现',
        	        'data' => array('url' => U('Mobile/User/gold')),
        	    );
        	    return  $this->ajaxReturn($return_arr);
        	}
        	if($money > $user['pay_gold_TX']){
        	    $return_arr = array(
        	        'status' => -1,
        	        'msg' => '提现失败,金酒币不足',
        	        'data' => array('url' => U('Mobile/User/gold')),
        	    );
        	    return  $this->ajaxReturn($return_arr);
        	}
        	$pay_gold = $user['pay_gold'] - $money;
        	$user_money = $user['user_money'] + $money; 
        	$r = M('users')->where('user_id',$this->user_id)->save(array('pay_gold'=>$pay_gold,'user_money'=>$user_money));
        	if($r){
        		income_action(2,5,'金酒币提现',$data['money'],$this->user_id);	//写入流水日志
        		$return_arr = array(
	                'status' => 1,
	                'msg' => '提现成功',
	                'data' => array('url' => U('Mobile/User/money_detail')),
	            );
		    	return  $this->ajaxReturn($return_arr);
        	}
        	else{
        		$return_arr = array(
	                'status' => -1,
	                'msg' => '提现失败',
	                'data' => array('url' => U('Mobile/User/gold')),
	            );
		    	return  $this->ajaxReturn($return_arr);
        	}
        }
        $this->assign('user',$user); 
        return $this->fetch();
    }
    
    /**
     *  金酒币明细
     */
    public function gold_detail(){  
    	$list = M('user_income')->where(array('uid'=>$this->user_id,'type'=>1))->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    /**
     *  余额明细
     */
    public function money_detail(){  
    	
    	$list1 = M('user_income')->where(array('uid'=>$this->user_id,'type'=>2))->select();
    	$list2 = M('account_log')->alias('a')->where('user_id='.$this->user_id.' and user_money!=0')->field('a.*,a.change_time as add_time,a.desc as source_name,a.user_money as amount')->select();
        $list = array_merge($list1,$list2);
        arsort($list);
        $this->assign('list',$list);
        return $this->fetch();
        
    }
    
    
    /**
     *  银酒币
     */
    public function silver(){   
        $user = M('users')->where('user_id',$this->user_id)->find();
        $rate = C('rate');
        //计算银酒币昨日收益
        $yesterday_income = M('user_income')->where(array('uid'=>$this->user_id,'type'=>0,'source'=>0))->whereTime('add_time', 'yesterday')->getField('SUM(amount)');
        $user['yesterday_income'] = empty($yesterday_income)?0:sprintf("%.2f", $yesterday_income);
        $this->assign('rate',$rate);
        $this->assign('user',$user);
        return $this->fetch();
    }
    
    
    /**
     *  银酒币兑换
     */
    public function silver_exchange(){  
    	
    	$user = M('users')->where('user_id',$this->user_id)->find(); 
    	if(IS_POST){
    	    $data = I('post.');
	    	$data['addtime'] = time();
	    	$data['uid'] = $this->user_id;
	    	if(is_int($data['pay_points']) || $data['pay_points']<0) exit('请不要非法操作！');
	    	if(empty($data['pay_points'])){
	    		$return_arr = array(
	                'status' => -1,
	                'msg' => '兑换数量不能为空',
	                'data' => '数量超过最大银酒币数量',
	            );
		    	return  $this->ajaxReturn($return_arr);
	    	}	
	    	if($data['pay_points']<=$user['pay_points']){
	    		$data['pay_gold'] = $data['pay_points']/100;//转换为金酒币
	    	    $user['pay_points'] -= $data['pay_points'];	
	    	    $user['pay_gold'] +=  $data['pay_gold'];
	    	}
	    	else{
	    		$return_arr = array(
	                'status' => -1,
	                'msg' => '请不要输入超过您的最大银酒币数量',
	                'data' => '数量超过最大银酒币数量',
	            );
		    	return  $this->ajaxReturn($return_arr);
	    	}
	    	$a = M('silver_exchange_record')->add($data);
	    	$b = M('users')->where('user_id',$this->user_id)->save($user);        
	    	if($a && $b){
	    		income_action(1,5,'金酒币兑换',$data['pay_gold'],$this->user_id);	//写入流水日志
	    		$return_arr = array(
	                'status' => 1,
	                'msg' => '兑换成功',
	                'data' => array('url' => U('Mobile/User/silver')),
	            );
		    	return  $this->ajaxReturn($return_arr);
	    	}
	    	else{
	    		$return_arr = array(
	                'status' => -1,
	                'msg' => '兑换失败',
	                'data' => '生成兑换记录时失败，请联系管理员',
	            );
		    	return  $this->ajaxReturn($return_arr);
	    	}	
    	}
        $this->assign('user',$user);
        return $this->fetch();
    }

    /**
     *  银酒币兑换明细
     */
    public function silver_exchange_detail(){   
        $list = M('silver_exchange_record')->where('uid',$this->user_id)->order('id DESC')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    /**
     *  银酒币明细
     */
    public function silver_detail(){   
        $list1 = M('user_income')->where(array('uid'=>$this->user_id,'type'=>0))->where('source_name <> "推广收益" and source <> 7')->order('id DESC')->select();
        $list2 = M('account_log')->alias('a')->where('user_id='.$this->user_id.' and pay_points!=0')->field('a.*,a.change_time as add_time,a.desc as source_name,a.pay_points as amount')->select();
        $list = array_merge($list1,$list2);
        arsort($list);
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    
    /*
     *一元夺宝 
     */
    public function indiana(){

        $lists_pay = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
                     ->where(array('a.uid'=>$this->user_id,'a.pay_status'=>0,'b.is_end'=>0))
                     ->field('a.*,b.goods_id,b.title,b.id as stage')->select();
        $lists_wait = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
                     ->where(array('a.uid'=>$this->user_id,'b.is_end'=>0,'a.pay_status'=>1))
                     ->field('a.*,b.goods_id,b.title,b.id as stage')->select();
        $lists_over = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
                     ->where(array('a.uid'=>$this->user_id,'b.is_end'=>1,'a.pay_status'=>1))
                     ->field('a.*,b.goods_id,b.title,b.id as stage')->select();
        //过滤掉未付款中已过期的订单（半个小时未付款则作废）
        foreach($lists_pay as $key=>$val){
        	if(time() >= $val['addtime']+1800){
        		$r = M('user_indiana')->where(array('id'=>$val['id']))->save(array('order_status'=>5));
        		if($r){
        			//通知用户订单作废
        		    SendMessage(0,1,"您有一笔一元夺宝订单编号为(".$val['order_sn'].")因半小时内未支付已自动作废，期待您重新参与！",array($this->user_id),"一元夺宝订单逾期未支付过期通知","/Mobile/Goods/indianaList");	
        		}
        		unset($lists_pay[$key]);
        	}
        }
        $this->assign('lists_pay',$lists_pay);
        $this->assign('lists_wait',$lists_wait);
        $this->assign('lists_over',$lists_over);
    	return $this->fetch();
    }
    
    /*
     *一元夺宝等待开奖 
     */
    public function indiana_wait(){
    	$id = I('id/d');
    	$indiana = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
                   ->where(array('a.id'=>$id,'b.is_end'=>0))
                   ->field('a.*,b.goods_id,b.title,b.price,b.id as stage')->find();
        $address = M('user_address')->where(array('address_id'=>$indiana['address_id']))->find();
        if(!$address){
            $address = M('user_address')->where(array('user_id'=>$indiana['uid'],'is_default'=>1))->find();  	
        }
        $indiana['indiana_number'] = json_decode($indiana['indiana_number'],true);          
        $this->assign('indiana',$indiana);          
        $this->assign('address',$address); 
    	return $this->fetch();
    }
    
    /*
     *一元夺宝已开奖 
     */
    public function indiana_over(){
    	$id = I('id/d');
    	$indiana = M('user_indiana')->alias('a')->join('indiana_sale b','b.id = a.indiana_id')
    	           ->join('goods c','c.goods_id = b.goods_id')
    	           ->join('users d','d.user_id = a.uid')
                   ->where(array('a.id'=>$id,'b.is_end'=>1))
                   ->field('a.*,b.goods_id,b.title,b.price,b.win_number,b.win_time,b.id as stage,c.goods_name,c.shop_price,d.nickname')->find();
        $address = M('user_address')->where(array('address_id'=>$indiana['address_id']))->find();
        if(!$address){
            $address = M('user_address')->where(array('user_id'=>$indiana['uid'],'is_default'=>1))->find();  	
        }
        $indiana['indiana_number'] = json_decode($indiana['indiana_number'],true);          
        if(!empty($indiana['shipping_info'])){
        	$indiana['shipping_info'] = json_decode($indiana['shipping_info'],true);
        	$indiana['shipping_info']['shipping_name'] = M('shipping')->where('shipping_id',$indiana['shipping_info']['shipping_id'])->getField('shipping_name');
        }       
        $this->assign('indiana',$indiana);          
        $this->assign('address',$address); 
    	return $this->fetch();
    }
    
    
     /*
     *一元夺宝增加收货地址
     */
    public function indiana_address(){
       $address_id = I('address_id/d');
       $id = I('id/d');
       $r = M('user_indiana')->where(array('id'=>$id))->save(array('address_id'=>$address_id));	
       if($r){
       	  echo json_encode(array('status'=>1,'msg'=>'设置成功！'));
       }
       else{
       	  echo json_encode(array('status'=>-1,'msg'=>'设置失败！'));
       }
    }
    
    
    /*
     *一元夺宝完成收货
     */
    public function indiana_receipt(){
       $id = I('id/d');
       $r = M('user_indiana')->where(array('id'=>$id,'uid'=>$this->user_id))->save(array('order_status'=>4));
       if($r){
       	  echo json_encode(array('status'=>1,'msg'=>'收货成功！'));
       }
       else{
       	  echo json_encode(array('status'=>-1,'msg'=>'收货失败！'));
       }
    }
    
    /**
     *  我参与的酒厂体验活动
     */
    public function activity(){   
        $activity = M('cellar_taste_form')->alias('a')
                   ->join('cellar_taste b','a.tid = b.id')
                   ->where('a.uid',$this->user_id)->select();
        //$activity = M('cellar_taste')->select();           
        $this->assign('activity',$activity);           
        return $this->fetch();
    }
    
    /*
     * 酒厂体验报名
     */
    public function activity_info(){
        $id = I("get.id");
//         $this->success("报名成功");
//         $this->error()
        if(IS_POST){
            $id = I("post.activityID");
            $data['tid'] = I("post.activityID");
            //判断该用户是否已报名此活动
            $result = M('cellar_taste_form')->where(array("tid"=>$data['tid'],"uid"=>$this->user_id))->find();
            if($result){
                $this->error("您已报名过此活动","/mobile/Cellar/activity_info/id/".$id);
            }
            $data['uid'] = $this->user_id;
            $data['name'] = I("post.name");
            $data['phone'] = I("post.tel");
            $data['num'] = I("post.sum");
            $data['addtime'] = time();
            $result = M('cellar_taste_form')->add($data);
            if($result){
                $this->success("报名成功","/mobile/User/activity_info/id/".$id);
            }else{
                $this->error("报名失败,请重试","/mobile/Caller/activity_info/id/".$id);
            }
        }
        $activityInfo = M("cellar_taste")->where("id",$id)->find();
        //获取报名报名信息
        $where['tid'] = $id;
        $where['uid'] = $this->user_id;
        $myActivityInfo = M("cellar_taste_form")->where($where)->find();
        if($myActivityInfo){
            $this->assign("isapply",1);
            $this->assign("myActivityInfo",$myActivityInfo);
        }else{
            $this->assign("isapply",0);
        }
        $this->assign("activityInfo",$activityInfo);
        return $this->fetch();
    }
    
    
    /**
     *  客服热线
     */
    public function service(){  
    	 
        return $this->fetch();
    }
    
    /**
     *  帮助中心
     */
    public function help(){  
    	$list = M('Article')->where("cat_id = 3 and is_open = 1")->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    /**
     *  平台公告
     */
    public function notice(){  
    	$list = M('Article')->where("cat_id = 2 and is_open = 1")->order('article_id DESC')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    /**
     *  文档详情
     */
    public function article(){  
    	$article_id = I('id/d',1);
    	$article = D('article')->where("article_id", $article_id)->find();
    	if($article){
    		$parent = D('article_cat')->where("cat_id",$article['cat_id'])->find();
    		$this->assign('cat_name',$parent['cat_name']);
    		$this->assign('article',$article);
    	}
        return $this->fetch();
    }
    
    /*
     * 发送验证码短信
     */
    public function sendSms() {
        $userinfo = $this->user;
        if(IS_AJAX){
        	$mobile = empty(I('mobile'))?$userinfo['mobile']:I('mobile'); 
            if($mobile){
                $smstype = I("post.smstype");
                $ordersn = I("post.ordersn");
                $code = rand(100000,999999);
                $mima = rand(100000,999999);
                $password = encrypt($mima);
                $_SESSION['mima']=$password;
                $param = array(
                       'code'  => $code,
                       'phone' => $mobile,
                       'mima'  => $mima,
                       'ordersn' => $ordersn,
                );
                $result = sendSMS2($mobile, $smstype, $param);
                $data1['mobile'] = $mobile;
                $data1['session_id'] = $this->session_id;
                $data1['add_time'] = time();
                $data1['code'] = $code;
                if($result['status'] === 1){//发送成功
                    //将验证码更新到数据库
                    $data1['status'] = 1;
                    //$_SESSION['code'] = $code;//验证码保留半小时
                    setcookie('mobile', $mobile, time()+1800, '/');//手机号保留半小时
                    M('sms_log')->add($data1);
                    $back['status'] = 1;
                    $back['msg'] = "发送成功";
                    $back['data'] = $result;
                }else{
                    $data1['status'] = 0;
                    $back['status'] = 0;
                    $back['msg'] = "发送失败";
                    $back['data'] = $result;
                    $data1['error_msg'] = $result['msg'];
                    M('sms_log')->add($data1);
                }
            }else{
                $back['status'] = 0;
                $back['msg'] = "手机号不能为空";
                $back['data'] = "接受验证码的手机不能为空";
            }
            echo json_encode($back);
            exit();
        }
    }
    
    /*
     * 验证验证码正确性
     */
    public function verifySMS(){
        $userinfo = $this->user;
        if (IS_AJAX){
            $code = I("post.verifycode");
            $where['session_id'] = $this->session_id;
            $where['mobile'] = $userinfo['mobile'];
            $result = M('sms_log')->where($where)->order("id DESC")->find();
            if($result){
                if($result['code'] == $code){
//                     if((time() - $result['add_time']) > 15*60){
//                         $back['status'] = 0;
//                         $back['msg'] = "验证码已过期，请重新获取验证码";
//                         $back['data'] = "验证码已过期，请重新获取验证码";
//                     }else{
                        $back['status'] = 1;
                        $back['msg'] = "验证码正确";
                        $back['data'] = $result;
//                     }
                }else{
                    $back['status'] = 0;
                    $back['msg'] = "验证码错误";
                    $back['data'] = "验证码错误";
                }
            }else{
                $back['status'] = 0;
                $back['msg'] = "验证码错误";
                $back['data'] = "该手机未发送过验证码";
            }
            echo json_encode($back);
            exit();
        }
    }
    
    /**
     * 个人中心资料修改
     */
    public function upd_userinfo() {
        if (IS_AJAX){
            $user_id = $this->user_id;
            $field = I("post.field");
            $value = I("post.value");
            if($field == "nickname" || $field == "password" ||  $field == "mobile"){//过滤其他信息修改
                if($field ==  "password"){
                    $data[$field] = md5(C("AUTH_CODE").$value);
                }else{
                    $data[$field] = $value;
                }
                $data['nickname'] = trim($data['nickname']);
                if(strlen($data['nickname']) > 20){
                	 $back["status"] = 0;
			         $back["msg"] = "昵称不能过长";
			         $back["data"] = "非法访问";
			         echo json_encode($back);
                     exit();
                }
                $result = M('users')->where("user_id",$user_id)->save($data);
                if($result){
                    $back["status"] = 1;
                    $back["msg"] = "修改成功";
                    $back["data"] = $result;
                }else{
                    $back["status"] = 0;
                    $back["msg"] = "修改失败";
                    $back["data"] = "记录修改失败";
                }
                echo json_encode($back);
                exit();
            }
        }
        $back["status"] = 0;
        $back["msg"] = "非法访问";
        $back["data"] = "非法访问";
        echo json_encode($back);
        exit();
    }
    
    
    /**
     * 签到
     */
    public function userSign() {
    	$user = M('users')->where('user_id',$this->user_id)->find();
    	$yesterday_sign = M('user_sign')->where('uid',$this->user_id)->whereTime('addtime', 'yesterday')->find();
    	$is_sign = M('user_sign')->where('uid',$this->user_id)->whereTime('addtime', 'today')->find();
    	if(empty($yesterday_sign) && empty($is_sign)){
    		$sign_num = 0; //判断是否连续签到，否则连续签到次数置零
    		M('users')->where('user_id',$this->user_id)->save(array('sign_num'=>$sign_num));
    	}
        if(IS_POST){
           if(!empty($is_sign)){
           	    $return_arr = array(
	                'status' => -1,
	                'msg' => '今天您已签到！',
	                'data' => '',
	            );
		    	return  $this->ajaxReturn($return_arr);
           }
           $num = I('post.sign_num'); 
           $sign['uid'] = $this->user_id;
       	   $sign['addtime'] = time();
       	   $r = M('user_sign')->add($sign);
       	   if($num<6){
       	   	  $num++;
       	   }
       	   else{
       	   	  $user['pay_points'] += 200;//签到7天，收益200银酒币
       	   	  $r = M('users')->where('user_id',$this->user_id)->save(array('pay_points'=>$user['pay_points']));
       	   	  if($r){
       	   	  	 income_action(0,2,'签到奖励',200,$this->user_id);//记录收益流水日志
       	   	  }
       	   	  else{
       	   	  	 $errorMsg = "UID为".$user['user_id']."的用户发放签到奖励失败——".date("Y-m-d H:i:s",time())."\r\n";
       	   	  	 log_error($errorMsg);
       	   	  }
       	   	  $num = 0;
       	   }
       	   $n = M('users')->where('user_id',$this->user_id)->save(array('sign_num'=>$num));
       	   if($r&&$n){
       	   	    $return_arr = array(
	                'status' => 1,
	                'msg' => '签到成功！',
	                'data' => '',
	            );
		    	return  $this->ajaxReturn($return_arr);
       	   }
       	   else{
       	   	    $return_arr = array(
	                'status' => -1,
	                'msg' => '签到失败！',
	                'data' => '',
	            );
		    	return  $this->ajaxReturn($return_arr); 
       	   }
        }
        $sign_num = M('users')->where('user_id',$this->user_id)->getField('sign_num');
        //$signLists = M('user_sign')->where('uid',$this->user_id)->limit(0,$sign_num)->order('id DESC')->select();
        $this->assign('sign_num',$sign_num);
        $this->assign('is_sign',$is_sign);
        //$this->assign('signList',$signLists);
        return $this->fetch();
        
    }
    
    
    /*
     * 我的系统消息
     */
    public function systemMessage() {
    	$start = empty(I('start'))?0:I('start');
    	$limit = empty(I('limit'))?20:I('limit');
        //消息列表(个体消息)
        $messsgelist = M('message')
                        ->alias('m')
                        ->join('f_user_message um',"um.message_id = m.message_id")
                        ->where("um.user_id",$this->user_id)
                        ->order('m.send_time desc')
                        ->field("m.*,um.category as umcategory,um.status,um.rec_id")
                        ->limit($start,$limit)
                        ->select();            
        //我的未查看通知消息总数
        $informCount =  M('user_message')
                        ->where("user_id=".$this->user_id." and category = 1 and status = 0")
                        ->count();
        //我的未查看物流消息总数
        $shppingMessageCount = M('user_message')
                        ->where("user_id=".$this->user_id." and category = 0 and status = 0")
                        ->count();
        $this->assign("shppingMessageCount",$shppingMessageCount);
        $this->assign("informCount",$informCount);
        $this->assign("messsgelist",$messsgelist);
        return $this->fetch();
    }
    
    
    /*
     * 查看消息
     */
    public function messageCheck() {
        if(IS_AJAX){
            $rec_id = I("post.rec_id");
            $r = M('user_message')->where("rec_id",$rec_id)->save(array("status"=>1));
            if($r){
            	echo json_encode(array('status'=>1,'msg'=>'消息状态更新成功！'));
            }
            else{
            	echo json_encode(array('status'=>-1,'msg'=>'消息状态更新失败！'));
            } 
            exit();
        }
    }
    
    
    public function updheadPic() {
        $imgsrc = I("post.imgsrc");
        $img = substr(strstr($imgsrc,','),1);
        $data= base64_decode($img);
        $path = "./public/upload/user/headPic/";
        if(!is_dir($path)){
            mkdir($path,777,true);
        }
        $path = $path.$this->user_id.".png";
        $result = file_put_contents($path,$data);
        if($result>0){
        	$path = substr_replace($path,'',0,1);
            $result1 = M('users')->where("user_id",$this->user_id)->save(array("head_pic"=>$path));
            if($result1 !== false){
                $back['status'] = 1;
                $back['msg'] = "操作成功";
                $back['data'] = $result1;
            }else{
                $back['status'] = 0;
                $back['msg'] = "操作失败";
                $back['data'] = "数据写入失败";
            }
        }else{
            $back['status'] = 0;
            $back['msg'] = "不支持此文件,请重试";
            $back['data'] = "头像更换失败";
        }
        echo json_encode($back);
        exit();
    }
    
    
    public function shipping_info() {
        $delivery_id = I("id");
        $delivery_info  = M('delivery_doc')->where("id",$delivery_id)->find();
//         //获取快递信息
//         $shipping_info = M('shipping_info')->where("delivery_id",$delivery_id)->find();
//         if(IS_AJAX){
//             //判断物流是否已完结
//             if(!empty($shipping_info)){
//                 if($shipping_info['state'] == 3){//已揽件
//                     $back['status'] = 1;
//                     $back['msg'] = "查询数据成功";
//                     $back['data'] = $result;
//                     echo json_encode($back);
//                     exit;
//                 }
//             }
//             $shippingcode = $delivery_info['shipping_code'];
//             $LogisticCode = $delivery_info['invoice_no'];
//             $CallBack = $delivery_id;//发货单号
// //             $shipping = C('shipping_code');
// //             $shippingname = "中通速递";
// //             $LogisticCode = '728802319545';
//             $result = get_shipping_info($shippingcode,$LogisticCode,$CallBack);
//             if($result['Success']){
//                 $back['status'] = 1;
//                 $back['msg'] = "查询成功";
//                 $back['data'] = $result;
//             }else{
//                 $back['status'] = 0;
//                 $back['msg'] = "查询失败";
//                 $back['data'] = $result;
//             }
//             echo json_encode($back);
//             exit;
//         }
//         $this->assign("shipping_info",json_decode($shipping_info['content'],true));
        $delivery_info['shipping_code'] ='YD';
        $delivery_info['invoice_no'] = "1000848280100";
        $delivery_info['order_sn'] = "ss";
        $shipping_info = getOrderTracesByJson($delivery_info['order_sn'],$delivery_info['shipping_code'],$delivery_info['invoice_no']);
        $this->assign("shipping_info",json_decode($shipping_info,true));
        $this->assign("delivery_info",$delivery_info);
        return $this->fetch();
    }
    
    
    public function tuikuan(){
    	include_once  "plugins/payment/weixin/weixin.class.php"; 
        $payment = new \weixin();
        $result = $payment->getMoney();
        
    }
    
    
    public function clearSession(){
    	Session::flush();
    } 

    public function fenxiang_income() {
        if(IS_AJAX){
            $user_id  = I('post.user_id');
            $type = I('post.type');
            switch ($type){
                case 1:
                    $source_name = "分享朋友圈获得收益";
                    break;
                case 2:
                    $source_name = "分享朋友获得收益";
                    break;
                case 3:
                    $source_name = "分享QQ获得收益";
                    break;
                case 4:
                    $source_name = "分享QQ空间获得收益";
                    break;
            }
            //判断今日是否已经获得过收益
            $share_info = M('user_income')
                            ->where("uid=$user_id and source = 7 and source_name = '$source_name'")
                            ->whereTime("add_time","today")
                            ->find();
            if(empty($share_info)){
                //收益
                $income = tpCache("basic.fx_silver");
                //增加收益
                $user_info = M('users')->where("user_id",$user_id)->find();
                $result = M('users')->where("user_id",$user_id)->save(array("pay_points"=>$user_info['pay_points']+$income));
                if($result){
                    //增加收益日志
                    income_action(0,7,$source_name,$income,$user_id);
                    $back['status'] = 1;
                    $back['msg'] = "分享成功,系统奖励您10银酒币";
                    $back['data'] = "分享成功";
                }else {
                    $back['status'] = 0;
                    $back['msg'] = "分享成功";
                    $back['data'] = "数据库写入失败";
                }
            }else{
                $back['status'] = 0;
                $back['msg'] = "分享成功，您今日已参与过此分享";
                $back['data'] = "今日已参与过此分享";
            }
        }else{
            $back['status'] = 0;
            $back['msg'] = "分享成功";
            $back['data'] = "非法访问";
        }
        echo json_encode($back);
        exit;
    }
    
    
    //测试自动提现
    public function txTest(){   
    	
        include_once "./plugins/payment/weixin/weixin.class.php";   
	    $payment = new \weixin(); 
	    $data = array('openid'=>'o0JIvv5fnouesE3bIFrldDV53_Ps','name'=>'王晨羽','amount'=>100,'ip'=>'222.209.47.77');       
        $payment->getMoney($data);  
        	
    }
    

    //退款
    function order_refund(){
        $pay_id = I("post.id");
        $pay_info = M("pay_log")->where("pay_id",$pay_id)->find();
        $out_refund_no = $pay_info['out_refund_no'];
        //查看是否已有退款信息
        $refund_info = M("refund_log")->where("out_refund_no",$out_refund_no)->find();
        if($refund_info){
            $back['status'] = 0;
            $back['msg'] = "请勿多次提交";
            $back['data'] = "已存在退款信息";
        }else{
            if($this->user_id == $pay_info['user_id']){
                $data['user_id'] = $this->user_id;
                $data['pay_id'] = $pay_info['pay_id'];
                $data['out_refund_no'] = $pay_info['out_trade_no'];
                $data['refund_fee'] = $pay_info['total_fee'];
                $data['status'] = 0;//未确认
                $result = M("refund_log")->add($data);
                if($result){
//                     $refund_result = order_WX_refund($result);//退款
                    //组装退款数据
                    $back['status'] = 1;
                    $back['msg'] = "退款申请成功";
                    $back['data'] = "退款申请成功";
                }else{
                    $back['status'] = 0;
                    $back['msg'] = "退款申请失败";
                    $back['data'] = "退款申请失败";
                }
            }else{
                $back['status'] = 0;
                $back['msg'] = "订单与账号不匹配";
                $back['data'] = "订单与账号不匹配";
            }

        }
        echo json_encode($back);
        exit;
    }
    
    
    //日常任务
    public function day_task(){   
    	//任务 1、完成资料（收货地址，头像上传）领取10银酒币
    	$userinfo = M('users')->where('user_id',$this->user_id)->find();
        if($userinfo['address_id'] && $userinfo['head_pic']){
        	$award[1]=10;
        	$source_name[1]='完成任务完善资料';
        	//查看是否领取奖励
        	$is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务完善资料'))->find();
        	if($is_give){
        		$task_res['t1'] = 2;
        	}
        	else{
        		$task_res['t1'] = 1;
        	}
        }else{
        	$task_res['t1'] = 0;
        }
        
        //任务2、完成第一次签到领取10银酒币
        $is_sign = M("user_sign")->where(array('uid'=>$this->user_id))->find();
        if($is_sign){
        	$award[2]=10;
        	$source_name[2]='完成任务第一次签到';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务第一次签到'))->find();
        	if($is_give){
        		$task_res['t2'] = 2;
        	}
        	else{
        		$task_res['t2'] = 1;
        	}
        }else{	
        	$task_res['t2'] = 0;
        }
        
        
        //任务3、每日累计推广人数达到10个领100银酒币
        $my_users_num = M('users')->where(array('first_leader'=>$this->user_id))->whereTime('reg_time','today')->count();
        $this->assign('my_users_num',$my_users_num);
        if($my_users_num >= 10){
        	$award[3]=100;
        	$source_name[3]='完成任务每日累计推广人数达到10个';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务每日累计推广人数达到10个'))->whereTime('add_time','today')->find();
        	if($is_give){
        		$task_res['t3'] = 2;
        	}
        	else{
        		$task_res['t3'] = 1;
        	}  	
        }else{
            $task_res['t3'] = 0;
        }
        
        
        //任务4、第一次购物，赠送银酒币50
        $my_amount = M('order')->where(array('user_id'=>$this->user_id,'order_status'=>2))->sum('order_amount');
        if($my_amount){
        	$award[4]=50;
        	$source_name[4]='完成任务第一次购物';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务第一次购物'))->find();
        	if($is_give){
        		$task_res['t4'] = 2;
        	}
        	else{
        		$task_res['t4'] = 1;
        	}  	
        }else{
            $task_res['t4'] = 0;
        }
        
        //任务5、单笔消费达到300-500，赠送银酒币300
        $amount_300 = M('order')->where(array('user_id'=>$this->user_id,'order_status'=>2))->where('order_amount>=300 and order_amount<=500')->whereTime('add_time','today')->field('order_amount')->find();
        if($amount_300){
        	$award[5]=300;
        	$source_name[5]='完成任务单笔消费达到300及以上';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务单笔消费达到300及以上'))->find();
        	if($is_give){
        		$task_res['t5'] = 2;
        	}
        	else{
        		M('task_log')->insert(array('user_id'=>$this->user_id,'tid'=>5,'status'=>0,'award'=>300,'addtime'=>time()));
        		$task_res['t5'] = 1;
        	}  	
        }else{
            $task_res['t5'] = 0;
        }
        
        
        //任务6、单笔消费达到500-1000，赠送银酒币500
        $amount_500 = M('order')->where(array('user_id'=>$this->user_id,'order_status'=>2))->where('order_amount>=500 and order_amount<=1000')->whereTime('add_time','today')->field('order_amount')->find();
        if($amount_500){
        	$award[6]=500;
        	$source_name[6]='完成任务单笔消费达到500及以上';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务单笔消费达到500及以上'))->find();
        	if($is_give){
        		$task_res['t6'] = 2;
        	}
        	else{
        		$task_res['t6'] = 1;
        	}  	
        }else{
            $task_res['t6'] = 0;
        }
        
        
        //任务7、单笔消费达到1000，赠送银酒币1000
        $amount_1000 = M('order')->where(array('user_id'=>$this->user_id,'order_status'=>2))->where('order_amount>=1000')->whereTime('add_time','today')->field('order_amount')->find();
        if($amount_1000){
        	$award[7]=1000;
        	$source_name[7]='完成任务单笔消费达到1000及以上';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务单笔消费达到1000及以上'))->find();
        	if($is_give){
        		$task_res['t7'] = 2;
        	}
        	else{
        		$task_res['t7'] = 1;
        	}  	
        }else{
            $task_res['t7'] = 0;
        }
        
        
        //任务8、累计参加10期平台的一元夺宝活动 奖励银酒币100
        $db_count = M('user_indiana')->where(array('uid'=>$this->user_id,'pay_status'=>1))->distinct(true)->field('indiana_id')->select();
        $db_count = count($db_count);
        $this->assign('db_count',$db_count);
        if($db_count >= 10){
        	$award[8]=100;
        	$source_name[8]='完成任务累计参加10期平台的一元夺宝活动';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务累计参加10期平台的一元夺宝活动'))->find();
        	if($is_give){
        		$task_res['t8'] = 2;
        	}
        	else{
        		$task_res['t8'] = 1;
        	}  	
        }else{
            $task_res['t8'] = 0;
        }


        //任务9、 累计参加30期平台一元夺宝活动奖励500银酒币
        if($db_count >= 30){
        	$award[9]=500;
        	$source_name[9]='完成任务累计参加30期平台的一元夺宝活动';
            $is_give = M('user_income')->where(array('uid'=>$this->user_id,'source'=>3,'source_name'=>'完成任务累计参加30期平台的一元夺宝活动'))->find();
        	if($is_give){
        		$task_res['t9'] = 2;
        	}
        	else{
        		$task_res['t9'] = 1;
        	}  	
        }else{
            $task_res['t9'] = 0;
        }        
      
        $n = I('post.n/d');
        if($n){//领奖操作
        	$s = "t".$n;
        	foreach($task_res as $key=>$val){
        		if($s==$key){
        			if($val==0){
        				echo json_encode(array('status'=>-1,'msg'=>'您还未完成任务！'));
        			}
        			if($val==1){
        				$r = M('users')->where('user_id',$this->user_id)->setInc('pay_points',$award[$n]);
						if($r){
						    income_action(0,3,$source_name[$n],$award,$this->user_id);
						    echo json_encode(array('status'=>1,'msg'=>'领奖成功！'));	
						}
						else{
							$errorMsg = "UID为".$this->user_id."的用户".$source_name."任务奖励".$award."银酒币发放失败——".date("Y-m-d H:i:s",time())."\r\n";
			                log_error($errorMsg);	
			                echo json_encode(array('status'=>-1,'msg'=>'领奖失败，请联系客服人员！'));
						}
        			} 
        			if($val==2){
        				echo json_encode(array('status'=>-1,'msg'=>'您已经领取过该奖励！'));
        			}
        		}
        	}
        	exit;
        }

        //print_r($task_res);
        $this->assign('task_res',$task_res);
        return $this->fetch();
    }
    
    
    
}

